//
//  StockTableQuoteCell.m
//  iStock Global
//
//  Created by Andy on 2010/10/2.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import "StockTableQuoteCell.h"
#import "tablecellgradent.h"
#import <QuartzCore/QuartzCore.h>

@implementation StockTableQuoteCell

@synthesize c0r0;
@synthesize c0r1;
@synthesize c0r2;
@synthesize c1r0;
@synthesize c1r1;
@synthesize c1r2;
@synthesize c2r0;
@synthesize c2r1;
@synthesize c2r2;

@synthesize zoom;
//@synthesize code;
//@synthesize name;
@synthesize lastprice;
@synthesize tradetime;
@synthesize tradeDate;
@synthesize UpDownView;
@synthesize updown;
@synthesize updownpercent;
@synthesize updownsigne;
#pragma mark -
#pragma mark  表格基本事件


- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
         downloadobject=[[DownloadData alloc]init];
        
         downloadobject.delgete=self;        
        
        
        if (ActivityIndicator==nil) {
           
            ActivityIndicator=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(130,150, 60, 60)];	
            ActivityIndicator.activityIndicatorViewStyle=UIActivityIndicatorViewStyleWhiteLarge;
            	
            [self.contentView addSubview:ActivityIndicator];
        }
        
        
        
		c0r0=[[UILabel alloc]init];		
		c0r1=[[UILabel alloc]init];		
		c0r2=[[UILabel alloc]initWithFrame:CGRectMake(10, 40, 100, 20)];		
		c1r0=[[UILabel alloc]init];		
		c1r1=[[UILabel alloc]init];		
		c1r2=[[UILabel alloc]init];		
		c2r0=[[UILabel alloc]init];		
		c2r1=[[UILabel alloc]init];		
		c2r2=[[UILabel alloc]init];				
		
		zoom=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 10, 60)];

		
		// Initialization code
		//name=[[UILabel alloc]initWithFrame:CGRectMake(10, 32, 125, 20)];
		//code=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 125, 20)];
		tradeDate=[[UILabel alloc]initWithFrame:CGRectMake(130, 32, 50, 20)];
		tradetime=[[UILabel alloc]initWithFrame:CGRectMake(185, 32, 50, 20)];
		lastprice=[[UILabel alloc]initWithFrame:CGRectMake(130, 10, 100, 20)];
		UpDownView=[[UIView alloc] initWithFrame:CGRectMake(230, 10,65, 40)];
		
		//將ㄒuiview 的四個角弄成有弧度 另外要加入 #import <QuartzCore/QuartzCore.h>
		UpDownView.layer.cornerRadius=10;	
		UpDownView.layer.masksToBounds = YES;
		//======================================================================
 		
		updown=[[UILabel alloc] initWithFrame:CGRectMake(240, 12,50, 20)];
		updownpercent=[[UILabel alloc] initWithFrame:CGRectMake(240, 28,50, 20)];		
		updownsigne=[[UILabel alloc]  initWithFrame:CGRectMake(235, 23,15, 15)];		
		
		updown.textAlignment=UITextAlignmentRight;
		updownpercent.textAlignment=UITextAlignmentRight;
		
		//code.font=[UIFont boldSystemFontOfSize:16];
		//name.font=[UIFont boldSystemFontOfSize:16];
		lastprice.font=[UIFont boldSystemFontOfSize:16];
		tradetime.font=[UIFont boldSystemFontOfSize:11];
		tradeDate.font=[UIFont boldSystemFontOfSize:11];
		updown.font=[UIFont boldSystemFontOfSize:13];		
		updownpercent.font=[UIFont boldSystemFontOfSize:12];			
		
		//name.textColor=[UIColor yellowColor];
		//code.textColor=[UIColor colorWithRed:1 green:1 blue:1 alpha:1];
		lastprice.textColor=[UIColor colorWithRed:1 green:1 blue:1 alpha:1];
		tradetime.textColor=[UIColor colorWithRed:1 green:1 blue:1 alpha:1];
		tradeDate.textColor=[UIColor colorWithRed:1 green:1 blue:1 alpha:1];		
		updown.textColor=[UIColor colorWithRed:1 green:1 blue:1 alpha:1];		
		updownpercent.textColor=[UIColor colorWithRed:1 green:1 blue:1 alpha:1];		
		
		//讓底色透明
		//name.backgroundColor=[UIColor clearColor];
		//code.backgroundColor=[UIColor clearColor];
		lastprice.backgroundColor=[UIColor clearColor];
		tradetime.backgroundColor=[UIColor clearColor];
		tradeDate.backgroundColor=[UIColor clearColor];
		UpDownView.backgroundColor=[UIColor clearColor];
	 	updown.backgroundColor=[UIColor clearColor];
		updownpercent.backgroundColor=[UIColor clearColor];
        //標記:Bloomberg 橘色        
        updownsigne.backgroundColor=[UIColor colorWithRed:255.0/255.0 green:157.0/255.0 blue:15.0/255.0 alpha:1.0];		
		  
        
        zoom.backgroundColor=[UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];;
        
        
		//設定cell backgroundView 的底色漸層次 設定view tablecellgrade.h tablecellgrade.m
		 self.backgroundView = [[[tablecellgradent alloc] initWithFrame:CGRectZero] autorelease];		
		
		[self.contentView addSubview:c0r0];
		[self.contentView addSubview:c0r1];
		[self.contentView addSubview:c0r2];		
		[self.contentView addSubview:c1r0];
		[self.contentView addSubview:c1r1];
		[self.contentView addSubview:c1r2];		
		[self.contentView addSubview:c2r0];
		[self.contentView addSubview:c2r1];
		[self.contentView addSubview:c2r2];		
		[self.contentView addSubview:zoom];
		
		//[self.contentView addSubview:name];
		//[self.contentView addSubview:code];	
		[self.contentView addSubview:lastprice];
		[self.contentView addSubview:tradetime];
		[self.contentView addSubview:tradeDate];	
		[self.contentView addSubview:UpDownView];
		[self.contentView addSubview:updown];	
		[self.contentView addSubview:updownpercent];
		//[self.contentView addSubview:updownsigne];
    }
    return self;
}
-(void)get_preday_close:(float)preday_close{
    lastday_close=preday_close;
    
}

//標記:日內走勢圖記憶體宣告實體與消滅 方法實作
-(void)get_cell_intraday_data:(NSMutableArray *) p_intraday_data 
           intraday_data_code:(NSMutableArray *) p_intraday_data_code 
         intraday_data_x_time:(NSMutableArray *) p_intraday_data_x_time
      intraday_graph_x_length:(NSMutableArray *) p_intraday_graph_x_length   
        intraday_graph_x_high:(NSMutableArray *) p_intraday_graph_x_high  
         intraday_graph_x_low:(NSMutableArray *) p_intraday_graph_x_low   
  intraday_graph_lastdayClose:(NSMutableArray *) p_intraday_graph_lastdayClose   
   intraday_graph_volume_high:(NSMutableArray *) p_intraday_graph_volume_high  
    intraday_graph_volume_low:(NSMutableArray *) p_intraday_graph_volume_low 
intraday_graph_selected_right:(NSMutableArray *) p_intraday_graph_selected_right  
 intraday_graph_selected_left:(NSMutableArray *) p_intraday_graph_selected_left   {
    
    cell_intraday_data=p_intraday_data;
    cell_intraday_data_code=p_intraday_data_code;
    cell_intraday_data_x_time=p_intraday_data_x_time;
    cell_intraday_graph_x_length=p_intraday_graph_x_length;
    cell_intraday_graph_x_high=p_intraday_graph_x_high;    
    cell_intraday_graph_x_low=p_intraday_graph_x_low;
    cell_intraday_graph_lastdayClose=p_intraday_graph_lastdayClose;
    cell_intraday_graph_volume_high=p_intraday_graph_volume_high;
    cell_intraday_graph_volume_low=p_intraday_graph_volume_low;
    cell_intraday_graph_selected_left=p_intraday_graph_selected_left;
    cell_intraday_graph_selected_right=p_intraday_graph_selected_right;    
    
}
- (void)setPosition:(UACellBackgroundViewPosition)newPosition {	
    [(tablecellgradent *)self.backgroundView setPosition:newPosition];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

#pragma mark -
#pragma mark  Yahoo ticker與Google ticker轉換
//標記:Yahoo ticker與Google ticker轉換 StockTableQuoteCell.m

//從yahoo 轉成 google
-(NSString *)TickerConvert_yahoo_google:(NSString *)yahoo_ticker{
    if (yahoo_ticker!=nil) {
        
        NSArray * code_array=[yahoo_ticker componentsSeparatedByString:@"."];        
        
        //標記:Add Target need Program
        
        if ([code_array count]==1) {
            //美國    
            return yahoo_ticker;
        }
        else if ([code_array count]==2) {
            //非美國
            //GOOGLE
            if ([[code_array objectAtIndex:1] isEqualToString:@"HK"]) {
                //香港
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"HKG"];                
                
            }
            else if ([[code_array objectAtIndex:1] isEqualToString:@"TW"] || [[code_array objectAtIndex:1] isEqualToString:@"TWO"] ) {
                //台灣                
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"TPE"];                
                
            }    
            else if ([[code_array objectAtIndex:1] isEqualToString:@"AX"]) {
                //澳洲
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"ASX"];                
                
            }
            else if ([[code_array objectAtIndex:1] isEqualToString:@"SS"] ) {
                //中國 上海               
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"SHA"];                
                
            }                
            else if ([[code_array objectAtIndex:1] isEqualToString:@"SZ"] ) {
                //中國 深圳                
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"SHE"];                
                
            }  
            else if ([[code_array objectAtIndex:1] isEqualToString:@"TO"]  ) {
                //加拿大                
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"TSE"];                
                
            } 
            else if ([[code_array objectAtIndex:1] isEqualToString:@"V"]  ) {
                //加拿大                
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"CVE"];                
                
            } 
            
            else if ([[code_array objectAtIndex:1] isEqualToString:@"NS"] ) {
                //印度               
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"NSE"];                
                
            }                
            else if ([[code_array objectAtIndex:1] isEqualToString:@"BO"] ) {
                //印度                
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"NSE"];                
                //雖然雅虎用BO 但是google
            }          
            else if ([[code_array objectAtIndex:1] isEqualToString:@"BE"] || [[code_array objectAtIndex:1] isEqualToString:@"BM"]  || [[code_array objectAtIndex:1] isEqualToString:@"DU"] || [[code_array objectAtIndex:1] isEqualToString:@"F"]  || [[code_array objectAtIndex:1] isEqualToString:@"HM"] || [[code_array objectAtIndex:1] isEqualToString:@"HA"] || [[code_array objectAtIndex:1] isEqualToString:@"MU"] || [[code_array objectAtIndex:1] isEqualToString:@"SG"] || [[code_array objectAtIndex:1] isEqualToString:@"DE"] ) {
                //德國  目前看來僅有 Deutsche Börse XETRA  電子交易所可以用         
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"ETR"];                
                
            } 
            else if ([[code_array objectAtIndex:1] isEqualToString:@"KS"] ) {
                //韓國                
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"SEO"];                
                
            }              
            else if ([[code_array objectAtIndex:1] isEqualToString:@"KQ"] ) {
                //韓國                
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"KDQ"];                
                
            }  
            else if ([[code_array objectAtIndex:1] isEqualToString:@"NZ"] ) {
                //紐西蘭                
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"NZE"];                
                
            }               
            else if ([[code_array objectAtIndex:1] isEqualToString:@"PA"] || [[code_array objectAtIndex:1] isEqualToString:@"NX"] ) {
                //法國                
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"EPA"];                
                
            }               
            else if ([[code_array objectAtIndex:1] isEqualToString:@"SA"] ) {
                //巴西                
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"SAO"];                
                
            }              
            else if ([[code_array objectAtIndex:1] isEqualToString:@"MX"] ) {
                //墨西哥  尚未有報價              
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"MXK"];                
                
            }  
            else if ([[code_array objectAtIndex:1] isEqualToString:@"SI"] ) {
                //新加坡  尚未有報價            
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"SIN"];                
                
            }             
            else if ([[code_array objectAtIndex:1] isEqualToString:@"L"] ) {
                //英國  有報價         
                return [NSString stringWithFormat:@"%@&x=%@",[code_array objectAtIndex:0],@"LON"];                
                
            }                 
            
            else{
                return [code_array objectAtIndex:0];
            }
            
            
            
        }
        else{
            return @"";
            
        }
    }
    else{
        
        return  @"";
        
    }
}
//從google 轉成 yahoo
-(NSString *)TickerConvert_google_yahoo:(NSString *)google_ticker{
  /*
    for (NSString *codd in data_code  ) {
        //因為是比較前面的字串是不是符合前面幾個字  
        if ([codd hasPrefix:google_ticker]) {
            return codd;
        }
        
        
    }
    */
    return @"";
}





#pragma mark -
#pragma mark  日內走勢圖

//標記:表格內展開出現日內走勢圖 TableCell內開始準備資料
-(void)drawGraph:(NSString *) asymbol{
   NSLog(@"table cell draw graph=%@",asymbol);
       
    [ActivityIndicator startAnimating];    
    
    
    if ([cell_intraday_data_code indexOfObject:asymbol ] !=NSNotFound  ) {
        //表示已經有下載過資料 
        NSLog(@"表示已經有下載過日內資料=%@",asymbol);
        //直接進行繪圖
        
        int indexa;
       
        
        indexa=[cell_intraday_data_code indexOfObject:asymbol];
        index_intraday=indexa;        
        
        lastday_close=[[cell_intraday_graph_lastdayClose objectAtIndex:indexa] floatValue];
        
        select_left=[cell_intraday_graph_selected_left objectAtIndex:indexa];
        select_right=[cell_intraday_graph_selected_right objectAtIndex:indexa];
        
        [self BeginDrawGraph:[cell_intraday_data_code objectAtIndex:indexa] 
                  data_array:[cell_intraday_data objectAtIndex:indexa] 
               data_array_x_time: [cell_intraday_data_x_time objectAtIndex:indexa]         
               lengthofgraph:[[cell_intraday_graph_x_length objectAtIndex:indexa] intValue]  
                      i_high:[[cell_intraday_graph_x_high objectAtIndex:indexa] floatValue] 
                       i_low:[[cell_intraday_graph_x_low objectAtIndex:indexa] floatValue] 
                 volume_high:[[cell_intraday_graph_volume_high objectAtIndex:indexa] doubleValue] 
                  volume_low:[[cell_intraday_graph_volume_low objectAtIndex:indexa] doubleValue]];        
        
        
        
    
    }
    else{
        NSLog(@"表示尚未下載過日內資料=%@",asymbol);  
        //先下載資料 下載完資料後才進行繪圖
        
        //yahoo
        NSString *urls_yahoo;
        urls_yahoo = [NSString stringWithFormat:@"http://chartapi.finance.yahoo.com/instrument/1.0/"];
        urls_yahoo=[urls_yahoo stringByAppendingString:asymbol]; //代碼 不含 .
        urls_yahoo=[urls_yahoo stringByAppendingString:@"/chartdata;type=quote;range=1d/csv/"];
        urls_yahoo = [urls_yahoo stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];	
        NSLog(@"urls_yahoo=%@",urls_yahoo);
        
        //註記：1d 表示一日資料 5d表示5日資料 只有這兩種模式
        //google
        int get_day;
        int get_second;
        get_day=1;
        get_second=60;
        
        NSString *urls_google;
        urls_google = [NSString stringWithFormat:@"http://www.google.com/finance/getprices?q="];
        urls_google=[urls_google stringByAppendingString:[self TickerConvert_yahoo_google: asymbol]]; //代碼 不含 .
        urls_google=[urls_google stringByAppendingString:[NSString stringWithFormat: @"&i=%i&p=%id&f=d,o,h,l,c,v",get_second,get_day]];
        urls_google = [urls_google stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];	        
        
        //標記:Yahoo與Google 資料選擇修改位置 分時資料-網址 
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];	
        if ([[prefs objectForKey:@"isYahoo"] boolValue]==YES) {
            //Yahoo
            //利用網路下載物件來下載資料
            
            if (downloadobject.loadingData==NO) {
                
                
                //[downloadobject release];
                //downloadobject=nil;
                //downloadobject=[[DownloadData alloc]init];
                
                //downloadobject.delgete=self;
                
                [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;        
                
                [downloadobject StartDownload:urls_yahoo  
                                   identifier:asymbol];
                
                
            }    
            
            
            
            
            
               
        }        
        else{
            //Google
            NSLog(@"url_google=%@",urls_google);  
            if (downloadobject.loadingData==NO) {
                
                
                //[downloadobject release];
                //downloadobject=nil;
               // downloadobject=[[DownloadData alloc]init];
                
               // downloadobject.delgete=self;
                
                [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;        
                
                [downloadobject StartDownload:urls_google  
                                   identifier:asymbol];
                
                
            }    
            
            
            
            
            
        }
        
        
        
        
        
        
        
               
        
    }
    
   
}
-(void)Download_Finish:(NSString *)datas Oidentifier:(NSString*)OutIdentifier{
    
    //NSLog(@"table quote cell _datas=%@",datas);    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;     
    
    //開始分析資料
    
    //宣告 取出來的資料
    NSString *ticker;
    //NSString *unit;
    NSString *timezone=nil;
   // NSString *currency;
    //NSString *gmtoffset;
    NSString *previous_close;
    NSString *Timestamp;
    NSString *labels;    
    NSString *errorid;     
    errorid=@"0";
    double dstart_time; //yahoo 定義的開始時間
    double dend_time;    
    Timestamp=@"";
    previous_close=@"0";    
    ticker=@"";    
    
    NSMutableArray *tempData;//暫時儲存 分時資料
    tempData=[[NSMutableArray alloc] init];
    
    NSMutableArray *labelsarray;//日期標簽
    labelsarray=[[NSMutableArray alloc] init];
    
    NSMutableArray *labelsarray_x_time;//日期標簽
    labelsarray_x_time=[[NSMutableArray alloc] init];        
    
    
    //標記:Yahoo與Google 資料選擇修改位置 分時資料-取出資料分析 
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];	
    if ([[prefs objectForKey:@"isYahoo"] boolValue]==YES) {
        //Yahoo
        //將資料分成列
        NSArray *csvLines ;	    
        csvLines = [datas  componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
        
        
        for (NSString *lines in csvLines ) {
            // NSLog(@"lines=%@",lines);
            //先找出基本資料
            NSArray * line_array=[lines componentsSeparatedByString:@":"];
            
            if ([line_array count]==2) {
                //表示符和基本資料格式
                if ([[line_array objectAtIndex:0] isEqualToString:@"ticker"]) {
                    ticker=  (NSString *)[line_array objectAtIndex:1] ;
                }
                else if ([[line_array objectAtIndex:0] isEqualToString:@"unit"]) {
                    //unit= (NSString *)[line_array objectAtIndex:1];
                }              
                else if ([[line_array objectAtIndex:0] isEqualToString:@"timezone"]) {
                    timezone= (NSString *)[line_array objectAtIndex:1];
                }            
                else if ([[line_array objectAtIndex:0] isEqualToString:@"currency"]) {
                    //currency= (NSString *)[line_array objectAtIndex:1];
                }     
                
                else if ([[line_array objectAtIndex:0] isEqualToString:@"gmtoffset"]) {
                    //gmtoffset= (NSString *)[line_array objectAtIndex:1];
                }             
                else if ([[line_array objectAtIndex:0] isEqualToString:@"previous_close"]) {
                    previous_close= (NSString *)[line_array objectAtIndex:1];
                    
                }             
                else if ([[line_array objectAtIndex:0] isEqualToString:@"Timestamp"]) {
                    Timestamp= (NSString *)[line_array objectAtIndex:1];
                    
                }  
                else if ([[line_array objectAtIndex:0] isEqualToString:@"labels"]) {
                    labels= (NSString *)[line_array objectAtIndex:1];
                    
                    NSArray * labels_array=[labels componentsSeparatedByString:@","];
                    for (NSString *slabels in labels_array) {
                        
                        [labelsarray addObject:slabels];
                        [labelsarray_x_time addObject:slabels];
                    }
                    
                }  
                else if ([[line_array objectAtIndex:0] isEqualToString:@"errorid"]) {
                    errorid= (NSString *)[line_array objectAtIndex:1];
                    
                }                  
            }
            else{
                //剩下的資料應該就是 日線內數據資料 將這些資料存到tempData
                [tempData addObject:lines];
                
                
            }
            
            
        }
        
        //針對取出的 日線內數據資料分析拆解  
        if ([tempData count] >0 && [errorid isEqualToString:@"0"]  ) {
            
            //暫存資料實體化
            
            graph_data_aray=[[NSMutableArray alloc] init];
            graph_data_x_time=[[NSMutableArray alloc] init];        
            graph_data_aray_raw=[[NSMutableArray alloc] init];       
            
            //取出原始的報價資料
            for (NSString *linedata in tempData ) {
                //分割 資料
                NSArray * Sarray=[linedata componentsSeparatedByString:@","];
                //檢查是否有 6個資料
                if ([Sarray count]==6) {
                    //將分時線資料存到 graph_data_aray_raw   陣列中
                    NSMutableDictionary *singdata;
                    singdata=[[NSMutableDictionary alloc] init];
                    
                    [singdata setObject: (NSString *)[Sarray objectAtIndex:0]  forKey:@"datetime"];                 
                    [singdata setObject: (NSString *)[Sarray objectAtIndex:1]  forKey:@"close"];   
                    [singdata setObject: (NSString *)[Sarray objectAtIndex:5]  forKey:@"volume"];              
                    
                    //注意：應該還可以加入開收高低與成交量資料 不過目前次處尚未加入
                    
                    [graph_data_aray_raw addObject:singdata];                
                    
                    [singdata release];
                    
                }
                
            }        
            
            //取出yahoo 定義的 開始與結束 時間
           // NSLog(@"Timestamp=%@",Timestamp);
            
            NSArray * Timestamp_array=[Timestamp componentsSeparatedByString:@","];    
            
            dstart_time=[[Timestamp_array objectAtIndex:0] doubleValue ];
            dend_time=[[Timestamp_array objectAtIndex:1] doubleValue ];    
            
            int LengthOftime;
            LengthOftime=0;
            
            
            float high,low;
            float volume_high=0;
            float volume_low=0;
            float pre_close;
            
            high=0;
            low=0;
            
            lastday_close=[previous_close floatValue]; //定義前一日收盤價 用在繪圖
            pre_close=[previous_close floatValue];//前一筆資料 如果目前的時間不合就用前一筆時間資料     
            
            //設計原理：從yahoo 取出來的資料是屬於不連續狀態,因此以yahoo定義的開始與結束時間當作循環,並且以此建立一個連續性的資料陣列 graph_data_aray
            
            for (double dtime = dstart_time ; dtime<=dend_time; dtime =dtime +60) {
                //循環計次使用
                LengthOftime=LengthOftime+1;            
                
                //開始進行判讀
                if ([graph_data_aray_raw count] >0) {
                    //如果不連續的資料還有
                    //取出第一筆的不連續資料
                    NSMutableDictionary *lastdata;
                    lastdata=[graph_data_aray_raw objectAtIndex:0];                
                    double d_last_time;
                    float d_close;
                    double d_volume;
                    
                    d_last_time=[[lastdata objectForKey:@"datetime"] doubleValue];
                    d_close=[[lastdata objectForKey:@"close"] floatValue];                
                    d_volume=[[lastdata objectForKey:@"volume"] floatValue];
                    //插曲 用來找所有資料中的最高價與最低價 此價格高低是用來匯圖形的上下區間
                    if (LengthOftime==1) {
                        high=d_close;
                        low=d_close;
                        volume_low=d_volume;
                        volume_high=d_volume;
                        
                    }
                    else{
                        if (d_close>high) {
                            high=d_close;
                        }
                        if (d_close<low) {
                            low=d_close;
                        }
                        if (d_volume>volume_high) {
                            volume_high=d_volume;
                        }
                        if (d_volume<volume_low) {
                            volume_low=d_volume;
                        }
                        
                    }
                    
                    double label_last_time; 
                    if ([labelsarray count]>0) {
                        label_last_time=[[labelsarray objectAtIndex:0] doubleValue] ;    
                    }                
                    else{
                        label_last_time=0;
                    }
                    
                    NSMutableDictionary *asingdata;
                    asingdata=[[NSMutableDictionary alloc] init];                
                    //比較是不是有股價資料
                    if (d_last_time>= dtime && d_last_time< dtime+60) {
                        //比對時間 如果不連續的資料的第一筆 落在這一分鐘內
                        //將此資料寫入到連續性的資料內 
                        
                        
                        
                        [asingdata setObject: [NSString stringWithFormat:@"%f",d_close]  forKey:@"close"];   
                        [asingdata setObject: [NSString stringWithFormat:@"%f",d_volume]  forKey:@"volume"];                      
                        
                        NSDate *start_time ;
                        start_time=[NSDate dateWithTimeIntervalSince1970:dtime   ];                 
                        NSDateFormatter *start_dateFormatter = [[NSDateFormatter alloc] init];
                        // start_dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                        start_dateFormatter.dateFormat = @"HH:mm";                    
                        
                        NSTimeZone *gmt =[NSTimeZone timeZoneWithName: [self Symbol_converTo_timeZoneWithName:ticker]];  
                        
                        // NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:timezone];
                        [start_dateFormatter setTimeZone:gmt];
                        NSString *string_start_time = [start_dateFormatter stringFromDate:start_time];                
                        [asingdata setObject: string_start_time    forKey:@"datetime"];                  
                        
                        
                        
                        [start_dateFormatter release];                      //將資料存入到連續的陣列中
                        
                        
                        
                        
                        
                        //將此資料轉入 所以將最近一筆消除
                        [graph_data_aray_raw removeObjectAtIndex:0];
                        
                        
                        
                    }
                    else{
                        //不連續的資料目前沒有落在此分鐘內 所以就用前一期的資料當作這一期資料使用
                        
                        
                        
                        [asingdata setObject: [NSString stringWithFormat:@"%f",pre_close]  forKey:@"close"];   
                        //沒有資料 成交量就設定為0
                        [asingdata setObject: [NSString stringWithFormat:@"%i",0]  forKey:@"volume"];                     
                        volume_low=0;
                        
                        
                        NSDate *start_time ;
                        start_time=[NSDate dateWithTimeIntervalSince1970:dtime   ];                 
                        NSDateFormatter *start_dateFormatter = [[NSDateFormatter alloc] init];
                        // start_dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                        start_dateFormatter.dateFormat = @"HH:mm";                     
                        NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:timezone];
                        [start_dateFormatter setTimeZone:gmt];
                        NSString *string_start_time = [start_dateFormatter stringFromDate:start_time];                
                        
                        [asingdata setObject: string_start_time    forKey:@"datetime"];                  
                        
                        
                        
                        [start_dateFormatter release];                     
                        
                        
                        
                        
                        
                    }
                    //比較是不是有時間標簽
                    if (label_last_time>= dtime && label_last_time< dtime+60) {
                        //比對時間 如果不連續的資料的第一筆 落在這一分鐘內
                        //將此資料寫入到連續性的資料內 
                        
                        
                        
                        [asingdata setObject: [NSNumber numberWithBool: YES]  forKey:@"labels"];   
                        
                        
                        
                        //將此資料轉入 所以將最近一筆消除
                        [labelsarray removeObjectAtIndex:0];
                        
                        
                        
                    }
                    else{
                        //不連續的資料目前沒有落在此分鐘內 所以就用前一期的資料當作這一期資料使用
                        
                        
                        
                        [asingdata setObject: [NSNumber numberWithBool: NO]  forKey:@"labels"];   
                        
                        
                        
                    }                
                    
                    [graph_data_aray addObject:asingdata];                 
                    [asingdata release];                 
                    //將收盤價存為最近ㄧ筆收盤價
                    pre_close=d_close;               
                    
                }
                else{
                    //不連續的資料已經使用完了 已經沒有資料
                    
                    
                }
                
                
                //處理x_time
                NSMutableDictionary *asingdata_xtime;
                asingdata_xtime=[[NSMutableDictionary alloc] init];             
                
                //date_time
                NSDate *start_time ;
                start_time=[NSDate dateWithTimeIntervalSince1970:dtime   ];                 
                NSDateFormatter *start_dateFormatter = [[NSDateFormatter alloc] init];
                start_dateFormatter.dateFormat =  @"HH:mm";
                NSTimeZone *gmt = [NSTimeZone timeZoneWithName: [self Symbol_converTo_timeZoneWithName:ticker]];
                [start_dateFormatter setTimeZone:gmt];
                NSString *string_start_time = [start_dateFormatter stringFromDate:start_time];                
                [asingdata_xtime setObject: string_start_time    forKey:@"datetime_x_time"];    
                //label
                double label_last_time_x; 
                if ([labelsarray_x_time count]>0) {
                    label_last_time_x=[[labelsarray_x_time objectAtIndex:0] doubleValue] ;    
                }                
                else{
                    label_last_time_x=0;
                }
                //比較是不是有時間標簽
                if (label_last_time_x>= dtime && label_last_time_x< dtime+60) {
                    //比對時間 如果不連續的資料的第一筆 落在這一分鐘內
                    //將此資料寫入到連續性的資料內 
                    
                    
                    
                    [asingdata_xtime setObject: [NSNumber numberWithBool: YES]  forKey:@"labels_x_time"];   
                    
                    
                    
                    //將此資料轉入 所以將最近一筆消除
                    [labelsarray_x_time removeObjectAtIndex:0];
                    
                    
                    
                }
                else{
                    //不連續的資料目前沒有落在此分鐘內 所以就用前一期的資料當作這一期資料使用
                    
                    
                    
                    [asingdata_xtime setObject: [NSNumber numberWithBool: NO]  forKey:@"labels_x_time"];   
                    
                    
                    
                }              
                
                
                
                
                
                [graph_data_x_time addObject:asingdata_xtime];            
                [asingdata_xtime release];
                [start_dateFormatter release];             
                
                
                
            }
            /*
             
             //檢查x_time
             for (NSString *nt in graph_data_x_time) {
             NSLog(@"graph_data_x_time=%@",nt);
             }
             
             */
            
            
            //紀錄曾經下載過資料
            if ([cell_intraday_data_code indexOfObject:[OutIdentifier retain]] ==NSNotFound) {
                
                
                [cell_intraday_data_code addObject:[OutIdentifier retain] ];
                //主要是因為在報價表重新更新時會移除 cell_intraday_data_code 這時會將所有的代碼順便宜除
                
                //標記:日內走勢圖記憶體宣告實體與消滅 把資料添加上去          
                
                [cell_intraday_data addObject:graph_data_aray];
                [cell_intraday_data_x_time addObject:graph_data_x_time];
                [cell_intraday_graph_x_length addObject:[NSString stringWithFormat:@"%i",LengthOftime ]];
                [cell_intraday_graph_x_high addObject:[NSString stringWithFormat:@"%f",high ]];
                [cell_intraday_graph_x_low addObject:[NSString stringWithFormat:@"%f",low ]];
                
                [cell_intraday_graph_volume_high addObject:[NSString stringWithFormat:@"%f",volume_high ]];
                [cell_intraday_graph_volume_low addObject:[NSString stringWithFormat:@"%f",volume_low ]];
                [cell_intraday_graph_lastdayClose addObject:[NSString stringWithFormat:@"%f",lastday_close ]];
                
                
                
                select_right=[ NSString  stringWithFormat :@"%i",0 ];
                select_left=[ NSString stringWithFormat:@"%i",0 ];
                
                [cell_intraday_graph_selected_left addObject:select_left];
                [cell_intraday_graph_selected_right addObject:select_right];
                
                
                index_intraday=[cell_intraday_graph_selected_right count]-1;            
                
            }
            /*
            for (NSDictionary *dd in graph_data_aray  ) {
                
                 NSLog(@"yahoo %@ %@ %@ %@" ,[dd objectForKey:@"datetime"] ,[dd objectForKey:@"close"],[dd objectForKey:@"volume"] ,[dd objectForKey:@"labels"]  );
                
            }               
             */
            
            
            
            //進入繪圖階段
            [self BeginDrawGraph:OutIdentifier 
                      data_array:graph_data_aray 
               data_array_x_time:graph_data_x_time 
                   lengthofgraph:LengthOftime 
                          i_high:high 
                           i_low:low
                     volume_high:volume_high 
                      volume_low:volume_low];        
            
            //清除資料
            //清除資料
             
            [graph_data_aray release];
            [graph_data_x_time release];
            [graph_data_aray_raw release];
             
   
        }
        else{
            //表示無資料可以進行繪圖
            //清除資料
            UIAlertView *al;
            al=[[UIAlertView alloc] initWithTitle:@"Data Error" message:@"Please remove this symbol!" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
            [al show];
            [al release];            
            
            
            [ActivityIndicator stopAnimating];	      
            
            //清除資料
            [graph_data_aray release];
            [graph_data_x_time release];
            [graph_data_aray_raw release];
            
            
            
        }
      
        
        
        
    }   
    
    else{
        //Google
        //將資料分成列
        NSArray *csvLines ;	    
        csvLines = [datas  componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
        
        int MARKET_OPEN_MINUTE=0;
        int MARKET_CLOSE_MINUTE=0;
        //int INTERVAL;
        //int TIMEZONE_OFFSET;
        int time_begin=0;
        //int time_begin_index;     
        NSString *DATA_SESSIONS;//主要是取出香港上下午盤的時間數據
        
        
        DATA_SESSIONS=@"";
         
         
        for (int i=0;i<[csvLines count];i++) {
            NSString *lines=[csvLines objectAtIndex:i] ;       
          //  NSLog(@"%i %@",i,lines );
            if (i<7) {
                //前段資料基本的時間結構
                NSArray * line_array=[lines componentsSeparatedByString:@"="];            
                if ([line_array count]==2) {
                    
                    if ([[line_array objectAtIndex:0] isEqualToString:@"MARKET_OPEN_MINUTE"]) {
                        MARKET_OPEN_MINUTE=[[line_array objectAtIndex:1] intValue];
                    }
                    else  if ([[line_array objectAtIndex:0] isEqualToString:@"MARKET_CLOSE_MINUTE"]) {
                        MARKET_CLOSE_MINUTE=[[line_array objectAtIndex:1] intValue];
                    }                
                    else  if ([[line_array objectAtIndex:0] isEqualToString:@"INTERVAL"]) {
                       // INTERVAL=[[line_array objectAtIndex:1] intValue];
                    }                   
                    else  if ([[line_array objectAtIndex:0] isEqualToString:@"TIMEZONE_OFFSET"]) {
                       // TIMEZONE_OFFSET=[[line_array objectAtIndex:1] intValue];
                    } 
                    else  if ([[line_array objectAtIndex:0] isEqualToString:@"DATA_SESSIONS"]) {
                        DATA_SESSIONS= [line_array objectAtIndex:1]  ;
                    }           
                }
                
            }
            else{
                NSArray * line_array=[lines componentsSeparatedByString:@","];               
                if ([line_array count]==6) {  
                    //開始取出資料
                    //判讀第一筆交易 以便取出時間
                    if ([lines hasPrefix:@"a"]) {
                        
                        //限制要有6個欄位資料
                        
                        time_begin=[[[line_array objectAtIndex:0] stringByReplacingOccurrencesOfString:@"a" withString:@""] intValue];
                        //time_begin_index=0;                    
                        
                         /*
                        //轉換時間
                        NSDate *start_time ;
                        start_time=[NSDate dateWithTimeIntervalSince1970:time_begin+time_begin_index *INTERVAL  ];                 
                        NSDateFormatter *start_dateFormatter = [[NSDateFormatter alloc] init];
                        start_dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";  
                        NSString *string_start_time = [start_dateFormatter stringFromDate:start_time];  
                        [start_dateFormatter release];                                               
                         [singdata setObject: string_start_time  forKey:@"datetime"]; 
                        */
                        
                        NSMutableDictionary *singdata;
                        singdata=[[NSMutableDictionary alloc] init];
                        
                        [singdata setObject: @"0"  forKey:@"datetime_index"];
                                        
                        [singdata setObject: [line_array objectAtIndex:1]  forKey:@"close"];   
                        [singdata setObject: [line_array objectAtIndex:5] forKey:@"volume"];                           
                        
                        [tempData addObject:singdata];                        
                        [singdata release];
                         //NSLog(@"string_start_time=%@ %f v=%@",string_start_time,[[line_array objectAtIndex:1] floatValue],[line_array objectAtIndex:5]  );                        
                        
                    }
                    else{
                        
                       // time_begin_index=[ [line_array objectAtIndex:0] intValue];
                        /*
                        //轉換時間
                        NSDate *start_time ;
                        start_time=[NSDate dateWithTimeIntervalSince1970:time_begin+time_begin_index*INTERVAL   ];                 
                        NSDateFormatter *start_dateFormatter = [[NSDateFormatter alloc] init];
                        start_dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";  
                        NSString *string_start_time = [start_dateFormatter stringFromDate:start_time];  
                        [start_dateFormatter release];
                        [singdata setObject: string_start_time  forKey:@"datetime"];  
                        */
                        
                         NSMutableDictionary *singdata;
                         singdata=[[NSMutableDictionary alloc] init];                        
                        
                                             
                        [singdata setObject: [line_array objectAtIndex:0]  forKey:@"datetime_index"];                         
                        [singdata setObject: [line_array objectAtIndex:1]  forKey:@"close"];   
                        [singdata setObject: [line_array objectAtIndex:5] forKey:@"volume"];                           
                        
                        [tempData addObject:singdata];                        
                        [singdata release];                        
                         /*
                        NSDate *start_time ;
                        start_time=[NSDate dateWithTimeIntervalSince1970:time_begin+time_begin_index*INTERVAL   ];                 
                        NSDateFormatter *start_dateFormatter = [[NSDateFormatter alloc] init];
                        start_dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";  
                        NSTimeZone *gmt =[NSTimeZone timeZoneWithName:[self Symbol_converTo_timeZoneWithName:OutIdentifier]];  
                        [start_dateFormatter setTimeZone:gmt];                         
                        
                        
                        NSString *string_start_time = [start_dateFormatter stringFromDate:start_time];  
                        
                        [start_dateFormatter release];                        
                         NSLog(@"%i time=%@ %f v=%@",time_begin_index,string_start_time ,[[line_array objectAtIndex:1] floatValue], [line_array objectAtIndex:5] );                        
                        */
                        
                        
                    }
                    //取出完資料 將資料匯入陣列中
                    
                    
                    
                    
                }            
                
                
            }
            // NSArray * line_array=[lines componentsSeparatedByString:@":"];
            
            
            
        }
      
       // NSLog(@"%i %i %i %i",MARKET_OPEN_MINUTE,MARKET_CLOSE_MINUTE,INTERVAL,TIMEZONE_OFFSET);        
       
        //將取出的資料存入陣列中準備進行繪圖
        if ([tempData count] >0) {
            //暫存資料實體化
            
            graph_data_aray=[[NSMutableArray alloc] init];
            graph_data_x_time=[[NSMutableArray alloc] init];        
            graph_data_aray_raw=[[NSMutableArray alloc] init];                
            
            //取出原始的報價資料
            for (int i=0;i<[tempData count];i++) {
                //分割 資料
                
                //將分時線資料存到 graph_data_aray_raw   陣列中
                NSMutableDictionary *singdata;
                singdata=[[NSMutableDictionary alloc] init];
                
                [singdata setObject: [[tempData objectAtIndex:i] objectForKey:@"datetime_index"]   forKey:@"datetime_index"];           
                [singdata setObject: [[tempData objectAtIndex:i] objectForKey:@"close"]   forKey:@"close"];   
                [singdata setObject: [[tempData objectAtIndex:i] objectForKey:@"volume"]   forKey:@"volume"];              
                
                int time_ind;
                time_ind=[[[tempData objectAtIndex:i] objectForKey:@"datetime_index"] intValue];
                
                NSDate *start_time ;
                start_time=[NSDate dateWithTimeIntervalSince1970:time_begin+time_ind*120  ];                 
                NSDateFormatter *start_dateFormatter = [[NSDateFormatter alloc] init];
                start_dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";  
                
                NSTimeZone *gmt =[NSTimeZone timeZoneWithName:[self Symbol_converTo_timeZoneWithName:OutIdentifier]];  
               [start_dateFormatter setTimeZone:gmt];                
                
                
                NSString *string_start_time = [start_dateFormatter stringFromDate:start_time];  
                
                [singdata setObject: string_start_time   forKey:@"datetime"];                 
                [start_dateFormatter release];
                
                
                
                
                //注意：應該還可以加入開收高低與成交量資料 不過目前次處尚未加入
                
                [graph_data_aray_raw addObject:singdata];                
                
                [singdata release];
            
                
            }                    
            
            //取出google 定義的 開始與結束 時間
            int morning_start,morning_end;
            int afternoon_start,afternoon_end;        
            
            if (![DATA_SESSIONS isEqualToString:@""]) {
                //表示有上下午盤時間資料 香港 中國
                
                //下面這段是用來 [MORNING,570,720],[AFTERNOON,810,960] 分解取出資料
                //標記:正規表示式 從文字中只取出數字
                NSString *regex=@"\\d+";
                // NSLog(@"run:%@",[DATA_SESSIONS componentsMatchedByRegex:regex]);
                NSArray *ttt=[DATA_SESSIONS componentsMatchedByRegex:regex];
                
                morning_start=[[ttt objectAtIndex:0] intValue] ;  
                morning_end=[[ttt objectAtIndex:1] intValue] ;              
                afternoon_start=[[ttt objectAtIndex:2] intValue] ;  
                afternoon_end=[[ttt objectAtIndex:3] intValue] ;  
                
                
            }    
            else{
                //表示無上下午盤
             //   NSLog(@"表示無上下午盤");
                morning_start=MARKET_OPEN_MINUTE ;
                morning_end=MARKET_CLOSE_MINUTE ;              
                afternoon_start=MARKET_OPEN_MINUTE ;  
                afternoon_end=MARKET_CLOSE_MINUTE ;              
                
            }
         //   NSLog(@"上下午盤時間資料 香港 中國=%i %i %i %i " ,  morning_start  ,morning_end,  afternoon_start ,afternoon_end );          
            
            
            
            
            //針對google得交易時間範圍 作循環
            int LengthOftime;
            LengthOftime=0;
            
            
            float high=0;
            float low=0;
            float volume_high=0;
            float volume_low=0;
            float pre_close;
            
             ; //定義前一日收盤價 用在繪圖
            pre_close=lastday_close;//前一筆資料 如果目前的時間不合就用前一筆時間資料     
           // NSLog(@"pre_close=%f",pre_close);
            
            for (int i=morning_start ;  i<=afternoon_end  ; i++) {
                //循環計次使用
                LengthOftime=LengthOftime+1;                   
                int ind;
                ind= i-morning_start;
                
                                
                
                int time_ind;
                time_ind=ind;
                
                NSDate *start_time ;
                
                start_time=[NSDate dateWithTimeIntervalSince1970:time_begin+time_ind*60  ];                 
                
                NSDateFormatter *start_dateFormatter = [[NSDateFormatter alloc] init];
                start_dateFormatter.dateFormat = @"HH:mm";  
                
                NSDateFormatter *start_dateFormatter_mm = [[NSDateFormatter alloc] init];
                start_dateFormatter_mm.dateFormat = @"mm";                         
                
                NSTimeZone *gmt =[NSTimeZone timeZoneWithName:[self Symbol_converTo_timeZoneWithName:OutIdentifier]];  
                [start_dateFormatter setTimeZone:gmt];                
                [start_dateFormatter_mm setTimeZone:gmt];                                        
                
                NSString *string_time = [start_dateFormatter stringFromDate:start_time];  
                NSString *string_time_mm = [start_dateFormatter_mm stringFromDate:start_time];  
                
                [start_dateFormatter release];                         
                [start_dateFormatter_mm release];                   
                
                
                if ( (i>=morning_start && i<=morning_end ) || (i>=afternoon_start-1 && i<=afternoon_end) ) {
                    //i 表示換算成一天的第幾分鐘
                    //ind 表示資料下載的序號
                    //下面這段區間是理論上全部的 交易時間
                                       
                   // NSLog(@"i=%i index=%i",i,ind );                    
                    
                    
                    //開始進行判讀
                    if ([graph_data_aray_raw count] >0) {
                        //如果不連續的資料還有
                        //取出第一筆的不連續資料
                        NSMutableDictionary *lastdata;
                        lastdata=[graph_data_aray_raw objectAtIndex:0];                
                       
                        int  d_last_time;
                        float d_close;
                        double d_volume;
                        //NSString *string_start_time;
                        //string_start_time=[lastdata objectForKey:@"datetime"];
                        d_last_time=[[lastdata objectForKey:@"datetime_index"] intValue];
                        d_close=[[lastdata objectForKey:@"close"] floatValue];                
                        d_volume=[[lastdata objectForKey:@"volume"] floatValue];
                        
                        
                        
                        
                        //插曲 用來找所有資料中的最高價與最低價 此價格高低是用來匯圖形的上下區間
                        if (LengthOftime==1) {
                            high=d_close;
                            low=d_close;
                            volume_low=d_volume;
                            volume_high=d_volume;
                            
                        }
                        else{
                            if (d_close>high) {
                                high=d_close;
                            }
                            if (d_close<low) {
                                low=d_close;
                            }
                            if (d_volume>volume_high) {
                                volume_high=d_volume;
                            }
                            if (d_volume<volume_low) {
                                volume_low=d_volume;
                            }
                            
                        }
                        
                       
                        
                        NSMutableDictionary *asingdata;
                        asingdata=[[NSMutableDictionary alloc] init];                
                        //比較是不是有股價資料
                     //  NSLog(@"i=%i index=%i d_last_time=%i ",i,ind,d_last_time );                           
                        
                        
                        if (d_last_time==ind) {
                            //比對時間 如果不連續的資料的第一筆 落在這一分鐘內
                            //將此資料寫入到連續性的資料內 
                            
                            
                            
                            [asingdata setObject: [NSString stringWithFormat:@"%f",d_close]  forKey:@"close"];   
                            [asingdata setObject: [NSString stringWithFormat:@"%f",d_volume]  forKey:@"volume"];                      
                            
                                                      
                            [asingdata setObject: string_time    forKey:@"datetime"];                  
                            
                            
                            
                            
                            //將此資料轉入 所以將最近一筆消除
                            [graph_data_aray_raw removeObjectAtIndex:0];
                            
                            
                            
                        }
                        else{
                            //不連續的資料目前沒有落在此分鐘內 所以就用前一期的資料當作這一期資料使用
                            [asingdata setObject: [NSString stringWithFormat:@"%f",pre_close]  forKey:@"close"];   
                            //沒有資料 成交量就設定為0
                            [asingdata setObject: [NSString stringWithFormat:@"%i",0]  forKey:@"volume"];
                            volume_low=0;
                            
                                                   
                            [asingdata setObject: string_time    forKey:@"datetime"];                             
                            
                             
                            
                        }                        
                        //比較是不是有時間標簽
                        if ([string_time_mm intValue]==0) {
                            //比對時間 如果不連續的資料的第一筆 落在這一分鐘內
                            //將此資料寫入到連續性的資料內 
                            
                            
                            
                            [asingdata setObject: [NSNumber numberWithBool: YES]  forKey:@"labels"];   
                            
                                                         
                            
                        }
                        else{
                            //不連續的資料目前沒有落在此分鐘內 所以就用前一期的資料當作這一期資料使用
                            
                            
                            
                            [asingdata setObject: [NSNumber numberWithBool: NO]  forKey:@"labels"];   
                            
                            
                            
                        }                                     
                        
                        
                        
                        [graph_data_aray addObject:asingdata];                 
                        [asingdata release];                 
                        //將收盤價存為最近ㄧ筆收盤價
                        pre_close=d_close;                         
                        
                        
                    }
                    else{
                    
                    
                    }
                    //處理x_time
                    NSMutableDictionary *asingdata_xtime;
                    asingdata_xtime=[[NSMutableDictionary alloc] init];             
                    
                    
                    [asingdata_xtime setObject: string_time    forKey:@"datetime_x_time"];    
                    //比較是不是有時間標簽
                    if ([string_time_mm intValue]==0) {
                        //比對時間 如果不連續的資料的第一筆 落在這一分鐘內
                        //將此資料寫入到連續性的資料內 
                        
                        
                        
                        [asingdata_xtime setObject: [NSNumber numberWithBool: YES]  forKey:@"labels_x_time"];   
                        
                        
                        
                        
                        
                    }
                    else{
                        //不連續的資料目前沒有落在此分鐘內 所以就用前一期的資料當作這一期資料使用
                        
                        
                        
                        [asingdata_xtime setObject: [NSNumber numberWithBool: NO]  forKey:@"labels_x_time"];   
                        
                        
                        
                    }              
                    
                    
                    [graph_data_x_time addObject:asingdata_xtime];            
                    [asingdata_xtime release];                    
                }
                 
                
                           
            
               
            }
            
            //紀錄曾經下載過資料
            if ([cell_intraday_data_code indexOfObject:[OutIdentifier retain]] ==NSNotFound) {
                
                
                [cell_intraday_data_code addObject:[OutIdentifier retain] ];
                //主要是因為在報價表重新更新時會移除 cell_intraday_data_code 這時會將所有的代碼順便宜除
                
                //標記:日內走勢圖記憶體宣告實體與消滅 把資料添加上去          
                
                [cell_intraday_data addObject:graph_data_aray];
                [cell_intraday_data_x_time addObject:graph_data_x_time];
                [cell_intraday_graph_x_length addObject:[NSString stringWithFormat:@"%i",LengthOftime ]];
                [cell_intraday_graph_x_high addObject:[NSString stringWithFormat:@"%f",high ]];
                [cell_intraday_graph_x_low addObject:[NSString stringWithFormat:@"%f",low ]];
                
                [cell_intraday_graph_volume_high addObject:[NSString stringWithFormat:@"%f",volume_high ]];
                [cell_intraday_graph_volume_low addObject:[NSString stringWithFormat:@"%f",volume_low ]];
                [cell_intraday_graph_lastdayClose addObject:[NSString stringWithFormat:@"%f",lastday_close ]];
                
                
                
                select_right=[ NSString  stringWithFormat :@"%i",0 ];
                select_left=[ NSString stringWithFormat:@"%i",0 ];
                
                [cell_intraday_graph_selected_left addObject:select_left];
                [cell_intraday_graph_selected_right addObject:select_right];
                
                
                index_intraday=[cell_intraday_graph_selected_right count]-1;            
                
            }
            
            /*
            for (NSDictionary *dd in graph_data_aray  ) {
                
                NSLog(@"google %@ %@ %@ %@" ,[dd objectForKey:@"datetime"] ,[dd objectForKey:@"close"],[dd objectForKey:@"volume"] ,[dd objectForKey:@"labels"]  );
                
            } 
             */
           // NSLog(@"graph_data_aray_raw count=%i",[graph_data_aray_raw count]);
            //進入繪圖階段
            [self BeginDrawGraph:OutIdentifier 
                      data_array:graph_data_aray 
               data_array_x_time:graph_data_x_time 
                   lengthofgraph:LengthOftime 
                          i_high:high 
                           i_low:low
                     volume_high:volume_high 
                      volume_low:volume_low];               
            
            
            
            
            //清除資料
            [graph_data_aray release];
            [graph_data_x_time release];
            [graph_data_aray_raw release];              
            
        
        }        
        else{
            NSLog(@"無分時資料");
            [ActivityIndicator stopAnimating];            
        }
               
        
    }    
    
    [labelsarray release];
    [tempData release];
    [labelsarray_x_time release];
}

-(void)Download_didFailWithError:(NSError *)error Oidentifier:(NSString*)OutIdentifier{
  //尚未完成 下載分時線資料錯誤 要記得完成
    UIAlertView *av;
	 
	av=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"No Internet Connection",@"No Internet Connection") message:NSLocalizedString(@"Tap 'Retry' to Reload Data ",@"Tap 'Retry' to Reload Data ") delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel",@"Cancel") otherButtonTitles:NSLocalizedString(@"Retry",@"Retry"),nil];
 	
	
	[av show];
    [av release];
	[ActivityIndicator stopAnimating];	    
} 

//標記:表格內展開出現日內走勢圖 縮減時的動作-消除走勢圖
-(void)hiden_secondTable{
    
   
    NSLog(@"hiden_secondTable_start");
   
    //將走勢圖移除並且消除記憶體
      
    [graph removeFromSuperlayer];
    [Chartview removeFromSuperview];
    [Chartview release];
    [graph release];
    Chartview=nil;
    graph=nil;    
    
    [graph_volume removeFromSuperlayer];
    [Chartview_volume removeFromSuperview];
    [Chartview_volume release];
    [graph_volume release];
    Chartview_volume=nil;
    graph_volume=nil;  
    
    [graph_range removeFromSuperlayer];
    [Chartview_range removeFromSuperview];
    [Chartview_range release];
    [graph_range release];
    Chartview_range=nil;
    graph_range=nil;        
           
         
    

         
    
}
#pragma mark -
#pragma mark  走勢圖資料匯入委託方法

//標記:表格內展開出現日內走勢圖 TableCell內開始繪圖
 
-(void)BeginDrawGraph:(NSString*)symbol
           data_array:(NSMutableArray *)p_graph_data_array 
    data_array_x_time:(NSMutableArray *)p_graph_data_array_x_time        
        lengthofgraph:(int)a_lengthgraph 
               i_high:(float)a_high
                i_low:(float)a_low
          volume_high:(float)a_volume_high
           volume_low:(float)a_volume_low{
    
       
    
    //如果之前已經有記憶體 則進行清除
    if (graph!=nil) {
        [self hiden_secondTable];
    }
   
    
    
    {
        //資料陣列
        graph_data_aray_real=p_graph_data_array;         
        graph_data_x_time=p_graph_data_array_x_time;         
        min_range=10 ; //限制兩軸最低距離    
        if ([graph_data_aray_real count]<10) {
            min_range=1;               
        }
        else{
            min_range=10 ;  
        }    
        
        
             
        
        int memory_right,memory_left;
        memory_left=[select_left intValue];
        memory_right=[select_right intValue];
        
        left_all=[graph_data_aray_real count]-1 ;         
        right_all=0;           
       
        left_all_x_time=[graph_data_x_time count]-1;
        right_all_x_time=0;
        
        
        if (memory_right==0 && memory_left==0) {
            //表示沒有設定
            //選定起始寬度
            int rangLength;
            
            rangLength=100;
            //rangLength=[graph_data_x_time count];            
            //最左邊
            {
                
                left_selected=[graph_data_aray_real count]-1 ;
                        
            }
            
            
            //最右邊
            {
                
                if ([graph_data_aray_real count]>rangLength) {
                    right_selected=[graph_data_aray_real count]-rangLength ;               
                }
                else{
                    right_selected=0 ;  
                }
                        
                
            }
             select_left=[ NSString stringWithFormat: @"%i",left_selected]; 
             select_right=[ NSString  stringWithFormat: @"%i",right_selected];            
            
            //將選擇的區間存入記憶體
            [cell_intraday_graph_selected_right replaceObjectAtIndex:index_intraday withObject:select_right];
            [cell_intraday_graph_selected_left replaceObjectAtIndex:index_intraday withObject:select_left];            
            
        }
        else{
            right_selected=[select_right intValue];
            left_selected=[select_left intValue]; 
            
            
            
        }
        
        //下面這段程式將會使graph 顯示所以已經交易的時段 用來控制版本
       right_selected=0;
        left_selected=[graph_data_aray_real count]-1;
        
                   
        
      
        
        //資料數量
        //lengthgraph_volume= [p_graph_data_array count] ;
        //lengthgraph_range= [p_graph_data_array count] ; 
        
        
        
        
        
         
        //graph高度  //volume高度  
        for (int x=right_selected  ; x<left_selected && x<[graph_data_aray_real count] ; x++ ) {
             
            NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:x];
            
            
            if (x==right_selected  ) {
                high_graph_selected= lastday_close;// [[tData objectForKey:@"close"] floatValue]  ;
                low_graph_selected=lastday_close;// [[tData objectForKey:@"close"] floatValue];
                                
            }
            else{
                if ([[tData objectForKey:@"close"] floatValue] >high_graph_selected) {
                    high_graph_selected=[[tData objectForKey:@"close"] floatValue];
                }
                if ([[tData objectForKey:@"close"] floatValue] <low_graph_selected) {
                    low_graph_selected=[[tData objectForKey:@"close"] floatValue];
                }
               
                
                
                
            }
            
            
            
        }        
        //volume高度  
        for (int x=right_selected  ; x<left_selected && x<[graph_data_aray_real count] ; x++ ) {
            
            NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:x];
            
            
            if (x==right_selected  ) {
                
                high_volume_selected=[[tData objectForKey:@"volume"] floatValue];  
                low_volume_selected=[[tData objectForKey:@"volume"] floatValue];                  
            }
            else{
                if ([[tData objectForKey:@"volume"] floatValue] >high_volume_selected) {
                    high_volume_selected=[[tData objectForKey:@"volume"] floatValue];
                }
                if ([[tData objectForKey:@"volume"] floatValue] <low_volume_selected) {
                    low_volume_selected=[[tData objectForKey:@"volume"] floatValue];
                }
                
                
                
            }
            
            
            
        }  
        
        high_volume_all=a_volume_high;
        low_volume_all=a_volume_low;
        
        high_graph_all=a_high;
        low_graph_all=a_low; 
        {
            if (lastday_close>=high_graph_all) {
                high_graph_all=lastday_close;
            }
            if (lastday_close<=low_graph_all) {
                low_graph_all=lastday_close;
            }
        
        }
        
        
    }
   
    //繪圖物件實體化
    {
        
        if (Chartview ==nil) {
            
            Chartview =[[CPTGraphHostingView alloc]initWithFrame:CGRectMake(20,70, 250, 130)];
            graph = [[CPTXYGraph alloc] init ];	
            Chartview.hostedGraph=graph;
            [self.contentView addSubview:Chartview];            
            
            Chartview_volume =[[CPTGraphHostingView alloc]initWithFrame:CGRectMake(20,200, 250, 50)];
            graph_volume = [[CPTXYGraph alloc] init ];	
            Chartview_volume.hostedGraph=graph_volume;
            [self.contentView addSubview:Chartview_volume];   
            
            Chartview_range =[[CPTGraphHostingView alloc]initWithFrame:CGRectMake(20,260, 250, 50)];
            graph_range = [[CPTXYGraph alloc] init ];	
            Chartview_range.hostedGraph=graph_range;
            [self.contentView addSubview:Chartview_range];             
            
            //標記:升級功能限制 日內走勢圖關閉            
            Chartview_range.hidden=NO;
            
        }
    
    }
    
    //graph 格式
    {
        //背景樣板
        CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
        
        [graph applyTheme:theme];        
        //讓走勢圖背景透明
       // [graph setBackgroundColor:[UIColor clearColor].CGColor ];
        
        //背景樣板
        CPTTheme *theme_volume = [CPTTheme themeNamed:kCPTDarkGradientTheme];
        [graph_volume applyTheme:theme_volume];        
        //讓走勢圖背景透明
        [graph_volume setBackgroundColor:[UIColor clearColor].CGColor ];        
        
        //背景樣板
        CPTTheme *theme_range = [CPTTheme themeNamed:kCPTDarkGradientTheme];
        [graph_range applyTheme:theme_range];        
        //讓走勢圖背景透明
        [graph_range setBackgroundColor:[UIColor clearColor].CGColor ];          
        
    }
   
    //graph的邊寬 
    {
        graph.paddingTop =0.0;
        graph.paddingBottom = 0.0;
        graph.paddingLeft =0.0;
        graph.paddingRight =0.0;
        graph.cornerRadius=0.0f;    
        
        graph_volume.paddingTop =0.0;
        graph_volume.paddingBottom = 0.0;
        graph_volume.paddingLeft =0.0;
        graph_volume.paddingRight =0.0;
        graph_volume.cornerRadius=0.0f;           
        
        graph_range.paddingTop =0.0;
        graph_range.paddingBottom = 0.0;
        graph_range.paddingLeft =0.0;
        graph_range.paddingRight =0.0;
        graph_range.cornerRadius=5.0f;         
        
    }
    
    //邊間 graph 與plotAreaFrame距離
    {
        //留下空間 以顯示x y軸的標籤
        graph.plotAreaFrame.paddingLeft = 0.0;
        graph.plotAreaFrame.paddingBottom = 10.0; 
        graph.plotAreaFrame.paddingTop = 20.0;         
        
        //留下空間 以顯示x y軸的標籤
        graph_volume.plotAreaFrame.paddingLeft = 0.0;
        graph_volume.plotAreaFrame.paddingBottom = 0.0;    
        
        //留下空間 以顯示x y軸的標籤
        graph_range.plotAreaFrame.paddingLeft = 0.0;
        graph_range.plotAreaFrame.paddingBottom = 10.0;          
        
    }
       
    //plotAreaFrame 周圍格式設定
    {
        CPTMutableLineStyle  *borderLineStyle = [CPTMutableLineStyle lineStyle];
        
        //標記:Bloomberg 橘色        
        borderLineStyle.lineColor = [CPTColor colorWithComponentRed:252.0/255.0 green:157.0/255.0 blue:15.0/255.0 alpha:1.0 ]; 
        
        borderLineStyle.lineWidth = 1.5f;
        
        CPTMutableLineStyle *borderLineStyle_range = [CPTMutableLineStyle lineStyle];
        borderLineStyle_range.lineColor = [CPTColor grayColor];
        borderLineStyle_range.lineWidth = 1.5f;        
        
        graph.plotAreaFrame.borderLineStyle =  borderLineStyle;	        
        graph.plotAreaFrame.cornerRadius = 0.0f; //四角的尖稅度     
   
        graph_volume.plotAreaFrame.borderLineStyle =  borderLineStyle;	        
        graph_volume.plotAreaFrame.cornerRadius = 0.0f; //四角的尖稅度  
        
        graph_range.plotAreaFrame.borderLineStyle =  borderLineStyle_range;	        
        graph_range.plotAreaFrame.cornerRadius = 5.0f; //四角的尖稅度         
        
    }
     
    
    
    //plotspace  
    {
        {
            plotSpace1= (CPTXYPlotSpace *)graph.defaultPlotSpace;
                     
            /*注意如果使用下面這段
             CPXYPlotSpace *plotSpace1 = [[CPXYPlotSpace alloc] init];
             則x y軸 將採用比例0-1 位置 而非絕對位置
             */        
            
            
            plotSpace1.delegate=self;        
            plotSpace1.identifier=@"plotSpace1";
            
            
            //定義 x y 的range 範圍
            //new_high=high; //主要是用在-(void)plotSpace:(CPPlotSpace *)space didChangePlotRangeForCoordinate:
            //new_low=low;     
            
            plotSpace1.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(low_graph_selected)  length:CPTDecimalFromFloat(high_graph_selected-low_graph_selected)];    
            plotSpace1.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(right_selected) length:CPTDecimalFromUnsignedInteger((left_selected-right_selected+1))]; 
            
            //使否可以手動 來移動plotspace
            // plotSpace1.allowsUserInteraction = YES;     
            
            [graph addPlotSpace:plotSpace1];        
        }
        //volume
        {
            plotSpace_volume= (CPTXYPlotSpace *)graph_volume.defaultPlotSpace;
            /*注意如果使用下面這段
             CPXYPlotSpace *plotSpace1 = [[CPXYPlotSpace alloc] init];
             則x y軸 將採用比例0-1 位置 而非絕對位置
             */        
            
            
            plotSpace_volume.delegate=self;        
            plotSpace_volume.identifier=@"plotSpace_volume";            
            
            //定義 x y 的range 範圍
            //new_high=high; //主要是用在-(void)plotSpace:(CPPlotSpace *)space didChangePlotRangeForCoordinate:
            //new_low=low;     
            
           plotSpace_volume.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(low_volume_selected)  length:CPTDecimalFromFloat(high_volume_selected-low_volume_selected)]; 
             //plotSpace_volume.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(low_volume)  length:CPDecimalFromFloat(low_volume+1000)];            
            plotSpace_volume.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(right_selected) length:CPTDecimalFromUnsignedInteger((left_selected-right_selected+1))]; 
            
            //使否可以手動 來移動plotspace
            // plotSpace1.allowsUserInteraction = YES;     
            
            [graph_volume addPlotSpace:plotSpace_volume];  
            
        }  
        //range
        {
            plotSpace_range= (CPTXYPlotSpace *)graph_range.defaultPlotSpace;
            /*注意如果使用下面這段
             CPXYPlotSpace *plotSpace1 = [[CPXYPlotSpace alloc] init];
             則x y軸 將採用比例0-1 位置 而非絕對位置
             */        
            
            
            plotSpace_range.delegate=self;        
            plotSpace_range.identifier=@"plotSpace_range";            
            
            //定義 x y 的range 範圍
                 
            
            plotSpace_range.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(low_graph_all)  length:CPTDecimalFromFloat(high_graph_all-low_graph_all)];    
            plotSpace_range.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(right_all_x_time) length:CPTDecimalFromUnsignedInteger(left_all_x_time-right_all_x_time+1)]; 
            
            //使否可以手動 來移動plotspace
            // plotSpace1.allowsUserInteraction = YES;     
            
            [graph_range addPlotSpace:plotSpace_range];        
        }  
        
        
    } 
    //label
    {
       
        graph_label_top =  [[CPTTextLayer alloc] init]  ;
        graph_label_top.bounds = CGRectMake(-5, 2, 18,300);
        CPTMutableTextStyle *textStyle1 = [ CPTMutableTextStyle textStyle];
        textStyle1.color    =  [CPTColor whiteColor];
        
        textStyle1.fontSize  = 12;	
        graph_label_top.textStyle=textStyle1;	
        [Chartview.hostedGraph addSublayer:graph_label_top];  
        
        
        
        //移動查價顯示graph 上層標籤
        {
            if (left_selected < [graph_data_aray_real count] && left_selected>=0) {
                
                NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:left_selected];
                
                float close;                 
                close=[[tData objectForKey:@"close"] floatValue] ;	
                
                graph_label_top.text=[NSString stringWithFormat:@"Time:%@  Price:%0.2f Vol:%i",[tData objectForKey:@"datetime"],close,[[tData objectForKey:@"volume"] intValue] ];                  
            } 
            
            
        }
        
        
        
         
    }
    {
      
    
    }
    
    //Plot 線圖
       
    {
        dataSourceLinePlot1=  [[CPTScatterPlot alloc] init]  ;
        dataSourceLinePlot1.identifier = @"Plot1";
        
        CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
        lineStyle.lineWidth = 1.0f;
        lineStyle.lineColor =[CPTColor whiteColor];        
        
        dataSourceLinePlot1.dataLineStyle =lineStyle;
        
        dataSourceLinePlot1.dataSource = self;	
        [graph addPlot:dataSourceLinePlot1 toPlotSpace:plotSpace1];	
        [dataSourceLinePlot1 release];
        
        //做漸層圖 如果想個走勢圖可以重疊 則中間的會凸顯出來
        //利用此方法可以模擬出中間取出中間一段 
        //標記:Bloomberg 橘色        
        CPTColor *areaColor_begin =  [CPTColor colorWithComponentRed:225.0/255.0 green:120.0/255.0 blue:20.0/255.0 alpha:1.0 ];        
         CPTColor *areaColor_end =  [CPTColor  clearColor ];          
        
        CPTGradient *areaGradient1 = [CPTGradient gradientWithBeginningColor:areaColor_begin endingColor:areaColor_end];
        areaGradient1.angle = -270.0f;
        CPTFill *areaGradientFill = [CPTFill fillWithGradient:areaGradient1];
        
        dataSourceLinePlot1.areaFill = areaGradientFill;
        dataSourceLinePlot1.areaBaseValue = CPTDecimalFromInt(low_graph_selected);          
    /*
        dataSourceLinePlot_preClose=  [[CPScatterPlot alloc] init]  ;
        dataSourceLinePlot_preClose.identifier = @"preClose";
        dataSourceLinePlot_preClose.dataLineStyle.lineWidth = 2.5f;
        dataSourceLinePlot_preClose.dataLineStyle.lineColor = [CPColor yellowColor];
        dataSourceLinePlot_preClose.dataSource = self;	
        //虛線格式
        dataSourceLinePlot_preClose.dataLineStyle.dashPattern = [NSArray arrayWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:3.0],nil];
        
        
        
        
        
        [graph addPlot:dataSourceLinePlot_preClose toPlotSpace:plotSpace1];	        
        [dataSourceLinePlot_preClose release];        
       */ 
        /*
        // Add plot symbols
        
        CPPlotSymbol *plotSymbol = [CPPlotSymbol diamondPlotSymbol];
        plotSymbol.fill = [CPFill fillWithColor:[CPColor blueColor]];
        plotSymbol.size = CGSizeMake(5.0, 5.0);
        dataSourceLinePlot1.plotSymbol = plotSymbol;        
       */
         
        //volemue
       /*
        dataSourceLinePlot_volume=  [[CPScatterPlot alloc] init]  ;
        dataSourceLinePlot_volume.identifier = @"Volume";
        dataSourceLinePlot_volume.dataLineStyle.lineWidth = 0.5f;
        dataSourceLinePlot_volume.dataLineStyle.lineColor = [CPColor yellowColor];
       
        dataSourceLinePlot_volume.dataSource = self;	
         
        //dataSourceLinePlot_volume.opacity = 0.0f; //因為要做動畫呈獻所以先關閉              
        [graph_volume addPlot:dataSourceLinePlot_volume toPlotSpace:plotSpace_volume];	
        [dataSourceLinePlot_volume release];
        
             
        
         
        //動畫呈獻
        CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
        fadeInAnimation.duration = 3.0f;
        fadeInAnimation.removedOnCompletion = NO;
        fadeInAnimation.fillMode = kCAFillModeForwards;
        fadeInAnimation.toValue = [NSNumber numberWithFloat:1.0];
        [dataSourceLinePlot_volume addAnimation:fadeInAnimation forKey:@"animateOpacity"];             
        //設定上漲下跌顏色
        //修改上漲下跌Ｋ線的檔案為:CPTradingRangePlot.h CPTradingRangePlot.m	
        */
         NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];	
        CPTColor *cupcolor=nil;
        CPTColor *cdowncolor=nil;
        //上漲
        if ([[prefs objectForKey:@"upColor"] isEqualToString:@"greenColor" ] ) {
        cupcolor=[CPTColor greenColor];
        } 
        else if ([[prefs objectForKey:@"upColor"] isEqualToString:@"redColor" ] ) {
        cupcolor=[CPTColor redColor];
        }         
        //下跌
        if ([[prefs objectForKey:@"downColor"] isEqualToString:@"redColor" ] ) {
        cdowncolor=[CPTColor redColor];
        } 
        else if ([[prefs objectForKey:@"downColor"] isEqualToString:@"greenColor" ] ) {
        cdowncolor=[CPTColor greenColor];
        }         
        
        
        
        
         
        
        
        //上漲成交量
        {
             
            
            dataSourceLinePlot_volume_up = [CPTBarPlot tubularBarPlotWithColor:cupcolor horizontalBars:NO];
            dataSourceLinePlot_volume_up.dataSource = self;
           
            CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
            lineStyle.lineWidth = 1.0f;
            lineStyle.lineColor =cupcolor; 
            dataSourceLinePlot_volume_up.lineStyle=lineStyle;
            dataSourceLinePlot_volume_up.fill = nil; 
            dataSourceLinePlot_volume_up.barWidth = CPTDecimalFromFloat(0.5);
            dataSourceLinePlot_volume_up.identifier = @"Volume_up";	
            dataSourceLinePlot_volume_up.delegate=self;
            
            //柱狀圖還必須調整基底位置 ***重要
            dataSourceLinePlot_volume_up.baseValue=CPTDecimalFromFloat(low_volume_selected);   
            [graph_volume addPlot:dataSourceLinePlot_volume_up toPlotSpace:plotSpace_volume];	        
        }
       	 
        //下跌成交量
        {
            
            
            
            dataSourceLinePlot_volume_down = [CPTBarPlot tubularBarPlotWithColor:cdowncolor horizontalBars:NO];
            dataSourceLinePlot_volume_down.dataSource = self;
            CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
            lineStyle.lineWidth = 1.0f;
            lineStyle.lineColor =cdowncolor;            
             dataSourceLinePlot_volume_down.lineStyle=lineStyle;
            dataSourceLinePlot_volume_down.fill = nil; 
            dataSourceLinePlot_volume_down.barWidth = CPTDecimalFromFloat(0.5);
            
            dataSourceLinePlot_volume_down.identifier = @"Volume_down";	
            dataSourceLinePlot_volume_down.delegate=self;
            
            //柱狀圖還必須調整基底位置 ***重要
            dataSourceLinePlot_volume_down.baseValue=CPTDecimalFromFloat(low_volume_selected);	 
            
            
            [graph_volume addPlot:dataSourceLinePlot_volume_down toPlotSpace:plotSpace_volume];	        
        }
                
        
        
        
        //volemue
        
        dataSourceLinePlot_range=  [[CPTScatterPlot alloc] init]  ;
        dataSourceLinePlot_range.identifier = @"Range";
        
        CPTMutableLineStyle *vlineStyle = [CPTMutableLineStyle lineStyle];
        vlineStyle.lineWidth = 1.0f;
       
        //標記:Bloomberg 橘色        
          
        
        vlineStyle.lineColor =[CPTColor  whiteColor ];
        
        dataSourceLinePlot_range.dataLineStyle=vlineStyle;
      //  dataSourceLinePlot_range.dataLineStyle.lineColor = [CPColor yellowColor];
        
        dataSourceLinePlot_range.dataSource = self;	
        
        //dataSourceLinePlot_volume.opacity = 0.0f; //因為要做動畫呈獻所以先關閉              
        [graph_range addPlot:dataSourceLinePlot_range toPlotSpace:plotSpace_range];	
        [dataSourceLinePlot_range release];
        /*
         //動畫呈獻
         CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
         fadeInAnimation.duration = 3.0f;
         fadeInAnimation.removedOnCompletion = NO;
         fadeInAnimation.fillMode = kCAFillModeForwards;
         fadeInAnimation.toValue = [NSNumber numberWithFloat:1.0];
         [dataSourceLinePlot_volume addAnimation:fadeInAnimation forKey:@"animateOpacity"];             
         */
         
         
        dataSourceLinePlot_range_selected=   [[CPTScatterPlot alloc] init]   ;
        dataSourceLinePlot_range_selected.identifier = @"Range_selected";
        CPTMutableLineStyle *clineStyle = [CPTMutableLineStyle lineStyle];
        clineStyle.lineWidth = 1.5f;
        clineStyle.lineColor =[CPTColor orangeColor];        
        dataSourceLinePlot_range_selected.dataLineStyle=clineStyle;
        //dataSourceLinePlot_range_selected.dataLineStyle.lineColor = [CPColor whiteColor];
        dataSourceLinePlot_range_selected.dataSource = self;	
        dataSourceLinePlot_range_selected.areaFill = areaGradientFill;
        dataSourceLinePlot_range_selected.areaBaseValue = CPTDecimalFromInt(low_graph_all);         
         
        
        [graph_range addPlot:dataSourceLinePlot_range_selected toPlotSpace:plotSpace_range];	        
        [dataSourceLinePlot_range_selected release];
        
        /*
        dataSourceLinePlot_range_preClose=  [[CPScatterPlot alloc] init] ;
        dataSourceLinePlot_range_preClose.identifier = @"range_preClose";
        dataSourceLinePlot_range_preClose.dataLineStyle.lineWidth = 0.5f;
        dataSourceLinePlot_range_preClose.dataLineStyle.lineColor = [CPColor yellowColor];
        dataSourceLinePlot_range_preClose.dataSource = self;	
        //虛線格式
        dataSourceLinePlot_range_preClose.dataLineStyle.dashPattern = [NSArray arrayWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:3.0],nil];        
        [graph_range addPlot:dataSourceLinePlot_range_preClose toPlotSpace:plotSpace_range];	        
        [dataSourceLinePlot_range_preClose release];
        */
        
        dataSourceLinePlot_range_volume = [CPTBarPlot tubularBarPlotWithColor:[CPTColor redColor] horizontalBars:NO];
        dataSourceLinePlot_range_volume.dataSource = self;
        CPTMutableLineStyle *glineStyle = [CPTMutableLineStyle lineStyle];
        glineStyle.lineWidth = 0.5f;
        glineStyle.lineColor = [CPTColor colorWithComponentRed:1.0 green:1.0 blue:1.0 alpha:1];        
        
        dataSourceLinePlot_range_volume.lineStyle =glineStyle;
        dataSourceLinePlot_range_volume.fill = nil; 
        dataSourceLinePlot_range_volume.barWidth =CPTDecimalFromFloat( 0.5);
        dataSourceLinePlot_range_volume.identifier = @"Range_Volume";	
        dataSourceLinePlot_range_volume.delegate=self;
        //volume 的基底位置 因為 x0 的位置有可能為負的 所以必須調整基底位置
        
        dataSourceLinePlot_range_volume.baseValue=CPTDecimalFromFloat(low_graph_all);	 
        [graph_range addPlot:dataSourceLinePlot_range_volume toPlotSpace:plotSpace_range];        
        
    }
       //Axes
	//軸的格式
    CPTMutableLineStyle *AxesLineStyle_x ;
    {
        AxesLineStyle_x= [ CPTMutableLineStyle   lineStyle];
        AxesLineStyle_x.lineWidth =1.0;
        //標記:Bloomberg 橘色        
                
        AxesLineStyle_x.lineColor = [CPTColor colorWithComponentRed:252.0/255.0 green:157.0/255.0 blue:15.0/255.0 alpha:1.0 ]; 	
        
        
    }
     CPTMutableTextStyle *xText_x;
    {
        xText_x= [ CPTMutableTextStyle   textStyle];
        xText_x.color = [CPTColor whiteColor];	
        xText_x.fontSize=8;    }
    
    CPTMutableLineStyle *AxesLineStyle_y ;
    {
        AxesLineStyle_y= [ CPTMutableLineStyle  lineStyle];
        AxesLineStyle_y.lineWidth =1.0;
       	
        //標記:Bloomberg 橘色        
        
        AxesLineStyle_y.lineColor = [CPTColor colorWithComponentRed:252.0/255.0 green:157.0/255.0 blue:15.0/255.0 alpha:1.0 ];         
        
        
        
    }
    CPTMutableTextStyle *xText_y;
    {
        xText_y= [ CPTMutableTextStyle  textStyle];
        xText_y.color = [CPTColor whiteColor];	
        xText_y.fontSize=10;    }    
    
    
    //選定的格式
    CPTMutableLineStyle *AxesLineStyle_selected = [CPTMutableLineStyle lineStyle];
    AxesLineStyle_selected.lineWidth =2.0;
    AxesLineStyle_selected.lineColor = [CPTColor whiteColor];    
    
    //lastday_close 軸線的格式
    CPTMutableLineStyle *AxesLineStyle_x_close = [CPTMutableLineStyle lineStyle];
    AxesLineStyle_x_close.lineWidth =2.0;
    AxesLineStyle_x_close.lineColor = [CPTColor whiteColor];     
    AxesLineStyle_x_close.dashPattern=[NSArray arrayWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:3.0],nil]; //虛線格式   
    
    CPTMutableLineStyle *majorGridLineStyle;    
	
    //graph 軸
    {
        //取出軸的參考
        CPTXYAxisSet *axisSet_graph = (CPTXYAxisSet *)graph.axisSet;	
        //設定 軸的參考
        CPTXYAxis *x = axisSet_graph.xAxis;    
        CPTXYAxis *y = axisSet_graph.yAxis;    
        CPTXYAxis *y_move_graph;//y2 為新增的移動查價使用 
        CPTXYAxis *x_graph_lastdayclose; 
        CPTXYAxis *x_graph_top_line;          
        //設定
        {
            //設定x軸
            {
                
                
                //設定x軸的艱巨
                x.majorIntervalLength = CPTDecimalFromString(@"100"); 
                
                //x 的在y軸上的起點(請注意 有分兩種模式 在graph.defaultPlotSpace下位置是一模一樣 另外一種[[CPXYPlotSpace alloc] init] 則是介於0-1 )
                x.orthogonalCoordinateDecimal = CPTDecimalFromFloat(low_graph_selected);
                
                //設定x軸的格式
                x.axisLineStyle=AxesLineStyle_x;
                x.labelTextStyle=xText_x; 
                x.majorTickLineStyle=AxesLineStyle_x;//軸上大間距的格式
                
                
                //計算間隔多少Ｋ線要呈現日期
                //int showKnumber;
                //showKnumber=6; //走勢圖上秀出6根ＫK線
                int kbarnumber;
                kbarnumber=(left_selected-right_selected+1)/6;
                
                
                NSMutableSet *customTickLocations ;
                customTickLocations=[[NSMutableSet alloc] init];
                
                for (int i=1; i<6; i++) {
                    
                    if (i*kbarnumber<(left_selected-right_selected+1) ) {
                        [customTickLocations addObject:[NSDecimalNumber numberWithInt:i*kbarnumber+right_selected]];	
                    }	
                    
                    
                }
                
                NSMutableArray *xAxisLabels ;
                xAxisLabels=[[NSMutableArray alloc] init];
                for (int i=1; i<6; i++) {
                    if (i*kbarnumber<(left_selected-right_selected+1) && i*kbarnumber<[graph_data_aray_real count]  ) {		
                        NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:i*kbarnumber+right_selected ];
                        
                                              
                        
                        [xAxisLabels addObject:(NSString *)[tData objectForKey:@"datetime"]];	
                       // NSLog(@"%@",(NSString *)[tData objectForKey:@"datetime"]  );
                    }
                }	
                
                NSUInteger labelLocation = 0;
                NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
                
                for (NSNumber *tickLocation in customTickLocations) {
                    
                    CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText: [xAxisLabels objectAtIndex:labelLocation++] textStyle:axisSet_graph.xAxis.labelTextStyle];
                    
                    newLabel.tickLocation = [tickLocation decimalValue];
                    newLabel.offset = axisSet_graph.xAxis.labelOffset + axisSet_graph.xAxis.majorTickLength;
                    newLabel.offset =  0.0;
                    
                    [customLabels addObject:newLabel];
                    
                    [newLabel release];
                }
                axisSet_graph.xAxis.majorTickLocations =	customTickLocations ;
                axisSet_graph.xAxis.axisLabels =  [NSSet setWithArray:customLabels];	          
                [customTickLocations release];
                [xAxisLabels release];                
                //當使用CPAxisLabelingPolicyNone 可以顯示格線
                x.labelingPolicy = CPTAxisLabelingPolicyNone;
                
                //格線格式
                majorGridLineStyle = [CPTMutableLineStyle lineStyle];
                majorGridLineStyle.lineWidth = 1.0;
                majorGridLineStyle.lineColor = [[CPTColor colorWithGenericGray:0.4] colorWithAlphaComponent:0.75];
                //虛線格式
                majorGridLineStyle.dashPattern=[NSArray arrayWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:3.0],nil];
                
                
                x.majorGridLineStyle = majorGridLineStyle;        
                
                x_graph_lastdayclose= [[( CPTXYAxis *)[ CPTXYAxis alloc] initWithFrame:CGRectZero] autorelease];
                x_graph_lastdayclose.labelingPolicy =  CPTAxisLabelingPolicyNone;
                x_graph_lastdayclose.orthogonalCoordinateDecimal = CPTDecimalFromFloat(lastday_close) ;
                x_graph_lastdayclose.coordinate = CPTCoordinateX;//此行很重要 如果沒有此行無法繪出第二條
                x_graph_lastdayclose.plotSpace = graph.defaultPlotSpace;
                x_graph_lastdayclose.axisLineStyle = AxesLineStyle_x_close;   
                
                x_graph_top_line= [[( CPTXYAxis *)[ CPTXYAxis alloc] initWithFrame:CGRectZero] autorelease];
                x_graph_top_line.labelingPolicy =  CPTAxisLabelingPolicyNone;
                x_graph_top_line.orthogonalCoordinateDecimal = CPTDecimalFromFloat(high_graph_selected) ;
                x_graph_top_line.coordinate = CPTCoordinateX;//此行很重要 如果沒有此行無法繪出第二條
                x_graph_top_line.plotSpace = graph.defaultPlotSpace;
                x_graph_top_line.axisLineStyle = AxesLineStyle_x;                 
            }
            
            //設定y軸
            {
                // Label y with an automatic label policy. 
                
                y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
                y.orthogonalCoordinateDecimal =  CPTDecimalFromFloat(right_selected);

                y.axisLineStyle=AxesLineStyle_y;
                y.labelTextStyle=xText_y;     
                y.minorTicksPerInterval = 0;//設定0可以將每個大區間的小區間模式取消
                y.majorTickLineStyle=AxesLineStyle_y;  
                
                y.majorGridLineStyle =majorGridLineStyle;
               
                //此段程式 是利用字串長度來計算出y軸與 label的距離 
                NSString *la;
                la=[NSString stringWithFormat:@"%.1f",lastday_close];
                y.labelOffset = -7.0 *la.length;                 
               
                //移動查價軸_graph
                y_move_graph= [[( CPTXYAxis *)[ CPTXYAxis alloc] initWithFrame:CGRectZero] autorelease];
                y_move_graph.labelingPolicy =  CPTAxisLabelingPolicyNone;
                y_move_graph.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0");
                y_move_graph.coordinate = CPTCoordinateY;//此行很重要 如果沒有此行無法繪出第二條
                y_move_graph.plotSpace = graph.defaultPlotSpace;
                y_move_graph.axisLineStyle = AxesLineStyle_y;
                
                
            }
            
            //將軸集合設定
            axisSet_graph.axes = [NSArray arrayWithObjects:x, y, y_move_graph,x_graph_lastdayclose,x_graph_top_line, nil];     
            //[y2 release];
            //[x_graph_lastdayclose release];
            
            
        }
    
    }
     
    //volume 軸
    {
        //取出軸的參考
        CPTXYAxisSet *axisSet_volume = (CPTXYAxisSet *)graph_volume.axisSet;	
        //設定 軸的參考
        CPTXYAxis *x_volume = axisSet_volume.xAxis;    
        CPTXYAxis *y_volume = axisSet_volume.yAxis;    
        CPTXYAxis *y_move_volume;//y2 為新增的移動查價使用   
                        
                
                //設定x軸的艱巨
                //x.majorIntervalLength = CPDecimalFromString(@"100"); 
                
                //x 的在y軸上的起點(請注意 有分兩種模式 在graph.defaultPlotSpace下位置是一模一樣 另外一種[[CPXYPlotSpace alloc] init] 則是介於0-1 )
                x_volume.orthogonalCoordinateDecimal = CPTDecimalFromFloat(low_volume_selected);
                
                //設定x軸的格式
                x_volume.axisLineStyle=AxesLineStyle_x;
                x_volume.labelTextStyle=xText_x; 
                x_volume.majorTickLineStyle=AxesLineStyle_x;//軸上大間距的格式
                
                
                //計算間隔多少Ｋ線要呈現日期
                //int showKnumber;
                //showKnumber=6; //走勢圖上秀出6根ＫK線
                int kbarnumber;
                kbarnumber=(left_selected-right_selected+1)/6;
                
                
                NSMutableSet *customTickLocations ;
                customTickLocations=[[NSMutableSet alloc] init];
                
                for (int i=1; i<6; i++) {
                    
                    if (i*kbarnumber<(left_selected-right_selected+1) ) {
                        [customTickLocations addObject:[NSDecimalNumber numberWithInt:i*kbarnumber+right_selected]];	
                    }	
                    
                    
                }
                
                NSMutableArray *xAxisLabels ;
                xAxisLabels=[[NSMutableArray alloc] init];
                for (int i=1; i<6; i++) {
                    if (i*kbarnumber<(left_selected-right_selected+1)) {		
                        NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:i*kbarnumber+right_selected ];
                        
                        
                        
                        [xAxisLabels addObject:(NSString *)[tData objectForKey:@"datetime"]];	
                        // NSLog(@"%@",(NSString *)[tData objectForKey:@"datetime"]  );
                    }
                }	
                NSUInteger labelLocation = 0;
                NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
                
                for (NSNumber *tickLocation in customTickLocations) {
                    
                    CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText: [xAxisLabels objectAtIndex:labelLocation++] textStyle:axisSet_volume.xAxis.labelTextStyle];
                    
                    newLabel.tickLocation = [tickLocation decimalValue];
                    newLabel.offset = axisSet_volume.xAxis.labelOffset + axisSet_volume.xAxis.majorTickLength;
                    newLabel.offset =  0.0;
                    
                    [customLabels addObject:newLabel];
                    
                    [newLabel release];
                }
              
               axisSet_volume.xAxis.majorTickLocations =	customTickLocations ;
               axisSet_volume.xAxis.axisLabels =  [NSSet setWithArray:customLabels];	          
                
                [customTickLocations release];
                [xAxisLabels release];
                
                
                //當使用CPAxisLabelingPolicyNone 可以顯示格線
                x_volume.labelingPolicy = CPTAxisLabelingPolicyNone;
                
                //格線格式
                majorGridLineStyle = [CPTLineStyle lineStyle];
                majorGridLineStyle.lineWidth = 1.0;
                majorGridLineStyle.lineColor = [[CPTColor colorWithGenericGray:0.4] colorWithAlphaComponent:0.75];
                //虛線格式
                majorGridLineStyle.dashPattern=[NSArray arrayWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:3.0],nil];
                
                
                x_volume.majorGridLineStyle = majorGridLineStyle;        
                
                
                
            
            
            //設定y軸
            {
                // Label y with an automatic label policy. 
                
                y_volume.labelingPolicy = CPTAxisLabelingPolicyNone;
                y_volume.orthogonalCoordinateDecimal =  CPTDecimalFromFloat(0);
                
                y_volume.axisLineStyle=AxesLineStyle_y;
                y_volume.labelTextStyle=xText_y;     
                y_volume.minorTicksPerInterval = 0;//設定0可以將每個大區間的小區間模式取消
                y_volume.majorTickLineStyle=AxesLineStyle_y;  
                
                y_volume.majorGridLineStyle =majorGridLineStyle;
                y_volume.labelOffset = -40.0;
                
                //移動查價軸_graph
                y_move_volume= [[( CPTXYAxis *)[ CPTXYAxis alloc] initWithFrame:CGRectZero] autorelease];
                y_move_volume.labelingPolicy =  CPTAxisLabelingPolicyNone;
                y_move_volume.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0");
                y_move_volume.coordinate = CPTCoordinateY;//此行很重要 如果沒有此行無法繪出第二條
                y_move_volume.plotSpace = graph_volume.defaultPlotSpace;
                y_move_volume.axisLineStyle = AxesLineStyle_y;             
                
            }
            
            //將軸集合設定
        axisSet_volume.axes = [NSArray arrayWithObjects:x_volume,y_volume, y_move_volume,   nil];   
        
    
        
        
    }    
    
    
     //range 軸
    {
        //取出軸的參考
        CPTXYAxisSet *axisSet_range = (CPTXYAxisSet *)graph_range.axisSet;	
        //設定 軸的參考
        CPTXYAxis *x_range = axisSet_range.xAxis;    
        CPTXYAxis *y_range = axisSet_range.yAxis;    
        CPTXYAxis *y_right;//y2 為新增的移動查價使用    
        CPTXYAxis *y_left;//y2 為新增的移動查價使用        
        CPTXYAxis *x_range_lastdayclose;           
        
        
        //設定x軸
        {
            
            
            //設定x軸的艱巨
            //x.majorIntervalLength = CPDecimalFromString(@"100"); 
            
            //x 的在y軸上的起點(請注意 有分兩種模式 在graph.defaultPlotSpace下位置是一模一樣 另外一種[[CPXYPlotSpace alloc] init] 則是介於0-1 )
            x_range.orthogonalCoordinateDecimal = CPTDecimalFromFloat(low_graph_all);
            
            //設定x軸的格式
            x_range.axisLineStyle=AxesLineStyle_x;
            x_range.labelTextStyle=xText_x; 
            x_range.majorTickLineStyle=AxesLineStyle_x;//軸上大間距的格式
            
            
            //計算間隔多少Ｋ線要呈現日期
            //int showKnumber;
            //showKnumber=6; //走勢圖上秀出6根ＫK線
            NSMutableSet *customTickLocations ;
            customTickLocations=[[NSMutableSet alloc] init];
            
            NSMutableArray *xAxisLabels ;
            xAxisLabels=[[NSMutableArray alloc] init];                
            
            
            
            for (int i=0; i<left_all_x_time; i++) {
                
                
                BOOL k;
                NSDictionary *tData = (NSDictionary *)[graph_data_x_time objectAtIndex:i ];                    
                
                k=[(NSNumber *)[tData objectForKey:@"labels_x_time"] boolValue];
                if (k==YES) {
                    [customTickLocations addObject:[NSDecimalNumber numberWithInt:i]];	
                   
                    [xAxisLabels addObject:(NSString *)[tData objectForKey:@"datetime_x_time"]];	                    
                                 
                }
                else{
                                   
                }
                
                                 
                
                
                
            }
	
            
            NSUInteger labelLocation = 0;
            NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
            
            for (NSNumber *tickLocation in customTickLocations) {
                
                CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText: [xAxisLabels objectAtIndex:labelLocation++] textStyle:axisSet_range.xAxis.labelTextStyle];
                
                newLabel.tickLocation = [tickLocation decimalValue];
                newLabel.offset = axisSet_range.xAxis.labelOffset + axisSet_range.xAxis.majorTickLength;
                newLabel.offset =  0.0;
                
                [customLabels addObject:newLabel];
                
                [newLabel release];
            }
            
            axisSet_range.xAxis.majorTickLocations =	customTickLocations ;
            axisSet_range.xAxis.axisLabels =  [NSSet setWithArray:customLabels];	          
            
            [customTickLocations release];
            [xAxisLabels release];
            
            //當使用CPAxisLabelingPolicyNone 可以顯示格線
            x_range.labelingPolicy = CPTAxisLabelingPolicyNone;
            
            //格線格式
            majorGridLineStyle = [CPTMutableLineStyle lineStyle];
            majorGridLineStyle.lineWidth = 1.0;
            majorGridLineStyle.lineColor = [[CPTColor colorWithGenericGray:0.4] colorWithAlphaComponent:0.75];
            //虛線格式
            majorGridLineStyle.dashPattern=[NSArray arrayWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:3.0],nil];
            
            
            x_range.majorGridLineStyle = majorGridLineStyle;        
            
            x_range_lastdayclose= [[( CPTXYAxis *)[ CPTXYAxis alloc] initWithFrame:CGRectZero] autorelease];
            x_range_lastdayclose.labelingPolicy =  CPTAxisLabelingPolicyNone;
            x_range_lastdayclose.orthogonalCoordinateDecimal = CPTDecimalFromFloat(lastday_close) ;
            x_range_lastdayclose.coordinate = CPTCoordinateX;//此行很重要 如果沒有此行無法繪出第二條
            x_range_lastdayclose.plotSpace = graph_range.defaultPlotSpace;
            x_range_lastdayclose.axisLineStyle = AxesLineStyle_x_close;              
            
            
            
        }
        
        //設定y軸
        {
            // Label y with an automatic label policy. 
            
            y_range.labelingPolicy = CPTAxisLabelingPolicyNone;
            y_range.orthogonalCoordinateDecimal =  CPTDecimalFromFloat(0.0);
            
            y_range.axisLineStyle=AxesLineStyle_y;
            y_range.labelTextStyle=xText_y;     
            y_range.minorTicksPerInterval = 0;//設定0可以將每個大區間的小區間模式取消
            y_range.majorTickLineStyle=AxesLineStyle_y;  
            
            y_range.majorGridLineStyle =majorGridLineStyle;
            y_range.labelOffset = -40.0;
            
            
            
        }
        
        //設定移動y軸
        {
            // Label y with an automatic label policy. 
            y_right= [[( CPTXYAxis *)[ CPTXYAxis alloc] initWithFrame:CGRectZero] autorelease];
            y_right.labelingPolicy =  CPTAxisLabelingPolicyNone;
            y_right.orthogonalCoordinateDecimal = CPTDecimalFromInt(right_selected);
            y_right.coordinate = CPTCoordinateY;//此行很重要 如果沒有此行無法繪出第二條
            y_right.plotSpace = graph_range.defaultPlotSpace;
            y_right.axisLineStyle = AxesLineStyle_selected;
            
            y_left= [[( CPTXYAxis *)[ CPTXYAxis alloc] initWithFrame:CGRectZero] autorelease];
            y_left.labelingPolicy =  CPTAxisLabelingPolicyNone;
            y_left.orthogonalCoordinateDecimal = CPTDecimalFromInt(left_selected);
            y_left.coordinate = CPTCoordinateY;//此行很重要 如果沒有此行無法繪出第二條
            y_left.plotSpace = graph_range.defaultPlotSpace;
            y_left.axisLineStyle = AxesLineStyle_selected;   
            
        }
      
        //將軸集合設定
        axisSet_range.axes = [NSArray arrayWithObjects:x_range,y_range, y_right, y_left,x_range_lastdayclose, nil];   
        
        
        
    }
    //[graph reloadData];
      
    [ActivityIndicator stopAnimating];     
}

#pragma mark -
#pragma mark  走勢圖-繪圖委託事件
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot{
    
	if ([(NSString *)plot.identifier isEqualToString:@"Plot1"]) {
        return left_selected-right_selected+1;
    }
    /*
    else if ([(NSString *)plot.identifier isEqualToString:@"preClose"]) {
        return left_selected-right_selected+1;
    }    
    */
	else if ([(NSString *)plot.identifier isEqualToString:@"Volume_up"]) {
		return left_selected-right_selected+1;
	} 
    else if ([(NSString *)plot.identifier isEqualToString:@"Volume_down"]) {
		return left_selected-right_selected+1;
	}    
    else if ([(NSString *)plot.identifier isEqualToString:@"Range"]) {
        
        
        
        return   [graph_data_aray_real count];
        
        
        
	} 
    
    else if ([(NSString *)plot.identifier isEqualToString:@"Range_Volume"]) {
        
        
        
        return [graph_data_aray_real count];
        
        
        
	}            
    
    
    else if ([(NSString *)plot.identifier isEqualToString:@"Range_selected"]) {
        
        
        
        return left_selected-right_selected+1;;
        
        
        
	} 
    /*
    else if ([(NSString *)plot.identifier isEqualToString:@"range_preClose"]) {
        
        
        
       return [graph_data_aray_real count];        
        
        
	}      
    */
	else {
		return 0;
	}
    
    
    
    
	
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
	
    
	NSDecimalNumber *num = [NSDecimalNumber zero];		
    
	if ([(NSString *)plot.identifier isEqualToString:@"Plot1"]) {
		  index=index+right_selected;
        
            if ( fieldEnum == CPTScatterPlotFieldY ) {
                
                NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:index];
                num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:[[tData objectForKey:@"close"] floatValue]];	
                               
            }
            if(fieldEnum== CPTTradingRangePlotFieldX) 
                num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index];
            
            
        }
        
    else if ([(NSString *)plot.identifier isEqualToString:@"Plot2"]) {
         
        
        if ( fieldEnum == CPTScatterPlotFieldY ) {
            
            NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:index];
            num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:[[tData objectForKey:@"close"] floatValue]];	
            
            
            
        }
        if(fieldEnum== CPTTradingRangePlotFieldX) 
            num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index];
        
        
    }
    
	 
	else if ([(NSString *)plot.identifier isEqualToString:@"Volume_up"]) {
        index=index+right_selected;
        
        //成交量 用是否為柱狀圖判斷
        switch ( fieldEnum ) {
            case CPTBarPlotFieldBarLocation:
                num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index ];
                break;
            case CPTBarPlotFieldBarTip:{
                NSDictionary *tData_1 ;
                              
                if (index==0) {
                     tData_1= (NSDictionary *)[graph_data_aray_real objectAtIndex:0]; 
                }
                else{
                     tData_1= (NSDictionary *)[graph_data_aray_real objectAtIndex:index-1]; 
                }
                NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:index];
                
                if ([[tData objectForKey:@"close"] floatValue]>[[tData_1 objectForKey:@"close"] floatValue]  ) {
                     num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:[[tData objectForKey:@"volume"] floatValue]];
                   // NSLog(@"v>0");
                }
                else{
                    num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:low_volume_selected];                
                   // NSLog(@"v<0");                
                
                }
                               
                
                
                break;
            } 
        }
             		
	}
    else if ([(NSString *)plot.identifier isEqualToString:@"Volume_down"]) {
        index=index+right_selected;
        
        //成交量 用是否為柱狀圖判斷
        switch ( fieldEnum ) {
            case CPTBarPlotFieldBarLocation:
                num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index ];
                break;
            case CPTBarPlotFieldBarTip:{
                NSDictionary *tData_1 ;
                
                if (index==0) {
                    tData_1= (NSDictionary *)[graph_data_aray_real objectAtIndex:0]; 
                }
                else{
                    tData_1= (NSDictionary *)[graph_data_aray_real objectAtIndex:index-1]; 
                }
                NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:index];
                
                if ([[tData objectForKey:@"close"] floatValue]<=[[tData_1 objectForKey:@"close"] floatValue]  ) {
                    num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:[[tData objectForKey:@"volume"] floatValue]];
                    //NSLog(@"v>0");
                }
                else{
                    num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:low_volume_selected];                
                   // NSLog(@"v<0");                
                    
                }
                
                
                
                break;
            } 
        }
        
	}    
    
    
    
    
    else if ([(NSString *)plot.identifier isEqualToString:@"Range"]) {
        
        
        if ( fieldEnum == CPTScatterPlotFieldY ) {
            
            NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:index];
            num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:[[tData objectForKey:@"close"] floatValue]];	
            
            
            
        }
        if(fieldEnum== CPTTradingRangePlotFieldX) 
            num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index];
        
        
    }
    else if ([(NSString *)plot.identifier isEqualToString:@"Range_Volume"]) {
        
        
        //成交量 用是否為柱狀圖判斷
        switch ( fieldEnum ) {
            case CPTBarPlotFieldBarLocation:
                num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index ];
                break;
            case CPTBarPlotFieldBarTip:{
                NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:index];
                float volume_high_low;
                float range_high_low;
                volume_high_low=high_volume_all-low_volume_all;
                range_high_low=high_graph_all-low_graph_all;
                float ratio;
                ratio=[[tData objectForKey:@"volume"] floatValue]/volume_high_low;
                num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat: range_high_low * ratio+low_graph_all ];                
                break;
            } 
        }
        
	}    
    
    
    else if ([(NSString *)plot.identifier isEqualToString:@"Range_selected"]) {
        index=index+right_selected;        
        if ( fieldEnum == CPTScatterPlotFieldY ) {
            
            NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:index];
            num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:[[tData objectForKey:@"close"] floatValue]];	
            
            
            
        }
        if(fieldEnum== CPTTradingRangePlotFieldX) 
            num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index];
        
        
    }
    
    
    
	return num;	   	  
    
}

#pragma mark -
#pragma mark  走勢圖-移動查價 與價格範圍調整

//移動查價時的公用函數:當點選graph 或volume 移動查價時使用
-(void)plotSpace1_plotSpace_volume_clickandmove:(NSString *)ClickOrMove plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDraggedEvent:(id)event atPoint:(CGPoint)point{

    //價格走勢圖上的移動查價
    NSDecimal plotPoint[2];         
    
    CPTXYPlotSpace *xySpace = (CPTXYPlotSpace *)space; 
    [xySpace plotPoint:plotPoint forPlotAreaViewPoint:point]; 
    
    
    
    //指定移動查價時 在graph volume 的移動查價軸位置
    {
        CPTMutableLineStyle *AxesLineStyle = [CPTMutableLineStyle lineStyle];
        AxesLineStyle.lineWidth =1.0;
        AxesLineStyle.lineColor = [CPTColor whiteColor];	
        
        CPTXYAxis *y_move_graph =[graph.axisSet.axes objectAtIndex:2]  ; 
        y_move_graph.orthogonalCoordinateDecimal =  CPTDecimalFromInt(  [[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPTCoordinateX]] intValue]   );    
        y_move_graph.axisLineStyle=AxesLineStyle;
        
        CPTXYAxis *y_move_volume =[graph_volume.axisSet.axes objectAtIndex:2]  ; 
        y_move_volume.orthogonalCoordinateDecimal =  CPTDecimalFromInt(  [[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPTCoordinateX]] intValue]   );    
        y_move_volume.axisLineStyle=AxesLineStyle;          
    }
    
    
    
    //移動查價顯示graph 上層標籤
    {
        
        
        if ([[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPTCoordinateX]] intValue]<[graph_data_aray_real count] && [[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPTCoordinateX]] intValue]>=0) {
            
            NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:[[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPTCoordinateX]] intValue] ];
            
            float close;                 
            close=[[tData objectForKey:@"close"] floatValue] ;	
            
            graph_label_top.text=[NSString stringWithFormat:@"Time:%@  Price:%0.2f Volume:%i",[tData objectForKey:@"datetime"],close,[[tData objectForKey:@"volume"] intValue] ];                  
        } 
        
        
    }
    
}

//點擊與移動中的通用函數
-(void)clickandmove:(NSString *)ClickOrMove plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDraggedEvent:(id)event atPoint:(CGPoint)point{
    
    if ([(NSString *)space.identifier isEqualToString:  @"plotSpace1"]) {
        //移動查價時的公用函數:當點選graph 或volume 移動查價時使用        
        [self plotSpace1_plotSpace_volume_clickandmove:ClickOrMove plotSpace:space shouldHandlePointingDeviceDraggedEvent:event atPoint:point];            
        
    }
    else if([(NSString *)space.identifier isEqualToString: @"plotSpace_volume"]){
      //移動查價時的公用函數:當點選graph 或volume 移動查價時使用
        [self plotSpace1_plotSpace_volume_clickandmove:ClickOrMove plotSpace:space shouldHandlePointingDeviceDraggedEvent:event atPoint:point];            
        
        
    }
    else  if ([(NSString *)space.identifier isEqualToString: @"plotSpace_range"]) {
        NSDecimal plotPoint[2];         
        
        CPTXYPlotSpace *xySpace = (CPTXYPlotSpace *)space; 
        [xySpace plotPoint:plotPoint forPlotAreaViewPoint:point]; 
        
        // NSLog(@"移動點plotPoint = %i, %i", 
        //   abs(range_right- [[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPCoordinateX]] intValue]),
        //   abs(range_left- [[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPCoordinateX]] intValue]));
        
        //設定y軸
        {
             
            //選定的格式
            CPTMutableLineStyle *AxesLineStyle_selected = [CPTMutableLineStyle lineStyle];
            AxesLineStyle_selected.lineWidth =2.0;
            AxesLineStyle_selected.lineColor = [CPTColor whiteColor];	
            
            //沒有選定的格式
            CPTMutableLineStyle *AxesLineStyle_no_selected =[CPTMutableLineStyle lineStyle];
            AxesLineStyle_no_selected.lineWidth =1.0;
            AxesLineStyle_no_selected.lineColor = [CPTColor grayColor];	
            //移動模式
            
            CPTMutableLineStyle *AxesLineStyle_move = [CPTMutableLineStyle lineStyle];
            AxesLineStyle_move.lineWidth =3.0;
           
            //標記:Bloomberg 橘色        
            AxesLineStyle_move.lineColor = [CPTColor colorWithComponentRed:225.0/255.0 green:120.0/255.0 blue:20.0/255.0 alpha:1.0 ];     
            
                       
            
            
            CPTXYAxis *y_right =[graph_range.axisSet.axes objectAtIndex:2]  ;
            CPTXYAxis *y_left =[graph_range.axisSet.axes objectAtIndex:3]  ;            
            
            //設計原理 將選定區域分成平均分四等分 1/4=右 2//4-3/4=移動 4/4=左邊
            float xRight,xLeft ;
            xRight=right_selected +(left_selected-right_selected)/4;
            xLeft=right_selected +(left_selected-right_selected)/4*3;
            move_length=left_selected- right_selected;
            
            if (  [[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPTCoordinateX]] intValue] <xRight    ) {
                //如果軸的絕對位置 越小值表示就是選定那個方向
                //選定右邊
                
                right_selected=[[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPTCoordinateX]] intValue];                
                //限制兩者距離
                if (left_selected-right_selected<min_range) {
                    
                    right_selected=left_selected-min_range;
                }
                //限制不可以超過最右邊
                if (right_selected<0  ) {
                    right_selected=0;
                }                
                
                y_right.orthogonalCoordinateDecimal =  CPTDecimalFromInt(right_selected);    
                y_right.axisLineStyle=AxesLineStyle_selected;
                y_left.axisLineStyle=AxesLineStyle_no_selected;               
                
            }
            else if([[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPTCoordinateX]] intValue] >xLeft  ){
                //選定左邊
                
                left_selected=[[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPTCoordinateX]] intValue];                
                //限制兩者距離                
                if (left_selected-right_selected<min_range) {
                    left_selected=right_selected+min_range;
                }
                //限制不可以超過最左邊
                if (left_selected>=[graph_data_aray_real count]) {
                    left_selected=[graph_data_aray_real count]-1;
                }
                
                y_left.orthogonalCoordinateDecimal =  CPTDecimalFromInt( left_selected   );    
                y_right.axisLineStyle=AxesLineStyle_no_selected;
                y_left.axisLineStyle=AxesLineStyle_selected;               
                
                
                
            }
            else{
                //移動中
                
                if ([[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPTCoordinateX]] intValue]-move_length/2 <0 ) {
                    
                    right_selected=0 ;                
                    left_selected=[[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPTCoordinateX]] intValue]+move_length/2 ;                
                    
                    y_right.orthogonalCoordinateDecimal =  CPTDecimalFromInt(right_selected);   
                    y_left.orthogonalCoordinateDecimal =  CPTDecimalFromInt( left_selected  );                  
                    
                    
                    y_right.axisLineStyle=AxesLineStyle_move;
                    y_left.axisLineStyle=AxesLineStyle_move;                        
                    
                }
                else if([[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPTCoordinateX]] intValue]+move_length/2 >left_all){
                    
                    right_selected=[[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPTCoordinateX]] intValue]-move_length/2 ;                
                    left_selected=left_all; 
                    
                    y_right.orthogonalCoordinateDecimal =  CPTDecimalFromInt(right_selected);   
                    y_left.orthogonalCoordinateDecimal =  CPTDecimalFromInt( left_selected  );                      
                    y_right.axisLineStyle=AxesLineStyle_move;
                    y_left.axisLineStyle=AxesLineStyle_move;                      
                    
                }
                else{
                    
                    right_selected=[[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPTCoordinateX]] intValue]-move_length/2 ;                
                    left_selected=[[NSDecimalNumber decimalNumberWithDecimal:plotPoint[CPTCoordinateX]] intValue]+move_length/2; 
                    
                    y_right.orthogonalCoordinateDecimal =  CPTDecimalFromInt(right_selected);   
                    y_left.orthogonalCoordinateDecimal =  CPTDecimalFromInt( left_selected  );                      
                    y_right.axisLineStyle=AxesLineStyle_move;
                    y_left.axisLineStyle=AxesLineStyle_move;                 
                }
                
            }
            
            //只有移動中才需要重繪圖
           // if ([ClickOrMove isEqualToString:@"move"]) {
                
                [graph_range reloadData];            
           // }
            
            //新的區間產生後要進入 shouldHandlePointingDeviceUpEvent 繼續執行
            
            
        }    
        
        
    }
}

//點擊
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDownEvent:(id)event atPoint:(CGPoint)point{
    [self clickandmove:@"click" plotSpace:space shouldHandlePointingDeviceDraggedEvent:event atPoint:point];
    
    
    return YES;  
}
//手勢移動中
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDraggedEvent:(id)event atPoint:(CGPoint)point{
    
    [self clickandmove:@"move" plotSpace:space shouldHandlePointingDeviceDraggedEvent:event atPoint:point];
         
    return YES;    
}
//手勢移動結束後
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceUpEvent:(id)event atPoint:(CGPoint)point{
    if ([(NSString *)space.identifier isEqualToString: @"plotSpace_range"]) {
        //設定x軸的格式
        CPTMutableLineStyle *AxesLineStyle_x ;
        {
            AxesLineStyle_x= [CPTMutableLineStyle   lineStyle];
            AxesLineStyle_x.lineWidth =1.0;
            //標記:Bloomberg 橘色        
            
            AxesLineStyle_x.lineColor = [CPTColor colorWithComponentRed:252.0/255.0 green:157.0/255.0 blue:15.0/255.0 alpha:1.0 ];   	 
        }
        CPTMutableTextStyle *xText_x;
        {
            xText_x= [ CPTMutableTextStyle   textStyle];
            xText_x.color = [CPTColor whiteColor];	
            xText_x.fontSize=8;    }
        CPTMutableLineStyle *AxesLineStyle_y ;
        {
            AxesLineStyle_y= [ CPTMutableLineStyle  lineStyle];
            AxesLineStyle_y.lineWidth =1.0;
            //標記:Bloomberg 橘色        
            
            AxesLineStyle_y.lineColor = [CPTColor colorWithComponentRed:252.0/255.0 green:157.0/255.0 blue:15.0/255.0 alpha:1.0 ];   	 
        }
        CPTMutableTextStyle *xText_y;
        {
            xText_y= [ CPTMutableTextStyle  textStyle];
            xText_y.color = [CPTColor whiteColor];	
            xText_y.fontSize=10;    }             
        
         CPTMutableLineStyle *majorGridLineStyle;        
        
        //選擇完範圍之後 才調整graph 區間
         {
            //計算新價的高低
            for (int x=right_selected  ; x<left_selected ; x++ ) {
                
                NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:x];
                
                
                if (x==right_selected  ) {
                    high_graph_selected= lastday_close;// [[tData objectForKey:@"close"] floatValue]  ;
                    low_graph_selected=lastday_close;// [[tData objectForKey:@"close"] floatValue];
                }
                else{
                    if ([[tData objectForKey:@"close"] floatValue] >high_graph_selected) {
                        high_graph_selected=[[tData objectForKey:@"close"] floatValue];
                    }
                    if ([[tData objectForKey:@"close"] floatValue] <low_graph_selected) {
                        low_graph_selected=[[tData objectForKey:@"close"] floatValue];
                    }
                    
                    
                }
                
                
                
            }
            
             //新的XY區間範圍
            plotSpace1.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromString([NSString stringWithFormat:@"%i",right_selected]) length:CPTDecimalFromString([NSString stringWithFormat:@"%i",left_selected-right_selected+1])];  
            
            plotSpace1.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(low_graph_selected)  length:CPTDecimalFromFloat(high_graph_selected-low_graph_selected)];            
            
             //top_line
             CPTXYAxis *x_graph_top_line =[graph.axisSet.axes objectAtIndex:4]  ; 
             x_graph_top_line.orthogonalCoordinateDecimal =  CPTDecimalFromFloat( high_graph_selected  );    
                  
             //新坐標軸
            CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;	
            CPTXYAxis *x = axisSet.xAxis;    
            CPTXYAxis *y = axisSet.yAxis;    
            x.orthogonalCoordinateDecimal = CPTDecimalFromString([NSString stringWithFormat:@"%f",low_graph_selected]);            
            y.orthogonalCoordinateDecimal = CPTDecimalFromString([NSString stringWithFormat:@"%i",right_selected]);            
            
            dataSourceLinePlot1.areaBaseValue = CPTDecimalFromInt(low_graph_selected);              
            
             //軸的格式
             x.axisLineStyle=AxesLineStyle_x;
             x.labelTextStyle=xText_x; 
             
             //計算間隔多少Ｋ線要呈現日期
             //int showKnumber;
             //showKnumber=6; //走勢圖上秀出6根ＫK線
             int kbarnumber;
              
                        kbarnumber=(left_selected-right_selected+1)/6;
             
             
             NSMutableSet *customTickLocations ;
             customTickLocations=[[NSMutableSet alloc] init];
             
             for (int i=1; i<6; i++) {
                 
                 if (i*kbarnumber<(left_selected-right_selected+1) ) {
                     [customTickLocations addObject:[NSDecimalNumber numberWithInt:i*kbarnumber+right_selected]];	
                 }	
                 
                 
             }
             
             NSMutableArray *xAxisLabels ;
             xAxisLabels=[[NSMutableArray alloc] init];
             for (int i=1; i<6; i++) {
                 if (i*kbarnumber<(left_selected-right_selected+1)) {		
                     NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:i*kbarnumber+right_selected ];
                     
                     
                     
                     [xAxisLabels addObject:(NSString *)[tData objectForKey:@"datetime"]];	
                     NSLog(@"%@",(NSString *)[tData objectForKey:@"datetime"]  );
                 }
             }	
             
             NSUInteger labelLocation = 0;
             NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
             
             for (NSNumber *tickLocation in customTickLocations) {
                 
                 CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText: [xAxisLabels objectAtIndex:labelLocation++] textStyle:axisSet.xAxis.labelTextStyle];
                 
                 newLabel.tickLocation = [tickLocation decimalValue];
                 newLabel.offset = axisSet.xAxis.labelOffset + axisSet.xAxis.majorTickLength;
                 newLabel.offset =  0.0;
                 
                 [customLabels addObject:newLabel];
                 
                 [newLabel release];
             }
             axisSet.xAxis.majorTickLocations =	customTickLocations ;
             axisSet.xAxis.axisLabels =  [NSSet setWithArray:customLabels];	          
             
             
             //當使用CPAxisLabelingPolicyNone 可以顯示格線
             x.labelingPolicy = CPTAxisLabelingPolicyNone;
             
             //格線格式
             majorGridLineStyle = [CPTMutableLineStyle lineStyle];
             majorGridLineStyle.lineWidth = 0.5;
             majorGridLineStyle.lineColor = [[CPTColor colorWithGenericGray:0.4] colorWithAlphaComponent:0.75];
             
             x.majorGridLineStyle = majorGridLineStyle;              
             
             
             
             
             [graph reloadData];
            
        }         
         //選擇完範圍之後 才調整volume 區間
        {
          //計算新量的高低
            for (int x=right_selected  ; x<left_selected ; x++ ) {
                
                NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:x];
                
                
                if (x==right_selected  ) {
                    
                    high_volume_selected=[[tData objectForKey:@"volume"] floatValue];  
                    low_volume_selected=[[tData objectForKey:@"volume"] floatValue];                  
                }
                else{
                    if ([[tData objectForKey:@"volume"] floatValue] >high_volume_selected) {
                        high_volume_selected=[[tData objectForKey:@"volume"] floatValue];
                    }
                    if ([[tData objectForKey:@"volume"] floatValue] <low_volume_selected) {
                        low_volume_selected=[[tData objectForKey:@"volume"] floatValue];
                    }
                    
                    
                    
                }
                
                
                
            }        
            
            //繪圖區間
            plotSpace_volume.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(low_volume_selected)  length:CPTDecimalFromFloat(high_volume_selected-low_volume_selected)]; 
            plotSpace_volume.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(right_selected) length:CPTDecimalFromUnsignedInteger((left_selected-right_selected+1))]; 
            
            //取出軸的參考
            CPTXYAxisSet *axisSet_volume = (CPTXYAxisSet *)graph_volume.axisSet;	
            //設定 軸的參考
            CPTXYAxis *x_volume = axisSet_volume.xAxis;    
              
            x_volume.orthogonalCoordinateDecimal = CPTDecimalFromFloat(low_volume_selected);
            x_volume.axisLineStyle=AxesLineStyle_x;
            
            //記住柱狀圖也要設定基底位置 否則會產生偏差
            dataSourceLinePlot_volume_up.baseValue=CPTDecimalFromFloat(low_volume_selected);             
            dataSourceLinePlot_volume_down.baseValue=CPTDecimalFromInt(low_volume_selected);
               
            
            //設定
            {
                //設定x軸
                {
                    
                    
                    //設定x軸的艱巨
                    //x.majorIntervalLength = CPDecimalFromString(@"100"); 
                    
                    //x 的在y軸上的起點(請注意 有分兩種模式 在graph.defaultPlotSpace下位置是一模一樣 另外一種[[CPXYPlotSpace alloc] init] 則是介於0-1 )
                    x_volume.orthogonalCoordinateDecimal = CPTDecimalFromFloat(low_volume_selected);
                    
                    //設定x軸的格式
                    x_volume.axisLineStyle=AxesLineStyle_x;
                    x_volume.labelTextStyle=xText_x; 
                    x_volume.majorTickLineStyle=AxesLineStyle_x;//軸上大間距的格式
                    
                    
                    //計算間隔多少Ｋ線要呈現日期
                    //int showKnumber;
                    //showKnumber=6; //走勢圖上秀出6根ＫK線
                    int kbarnumber;
                    kbarnumber=(left_selected-right_selected+1)/6;
                    
                    
                    NSMutableSet *customTickLocations ;
                    customTickLocations=[[NSMutableSet alloc] init];
                    
                    for (int i=1; i<6; i++) {
                        
                        if (i*kbarnumber<(left_selected-right_selected+1) ) {
                            [customTickLocations addObject:[NSDecimalNumber numberWithInt:i*kbarnumber+right_selected]];	
                        }	
                        
                        
                    }
                    
                    NSMutableArray *xAxisLabels ;
                    xAxisLabels=[[NSMutableArray alloc] init];
                    for (int i=1; i<6; i++) {
                        if (i*kbarnumber<(left_selected-right_selected+1)) {		
                            NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:i*kbarnumber+right_selected ];
                            
                            
                            
                            [xAxisLabels addObject:(NSString *)[tData objectForKey:@"datetime"]];	
                            // NSLog(@"%@",(NSString *)[tData objectForKey:@"datetime"]  );
                        }
                    }	
                    NSUInteger labelLocation = 0;
                    NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
                    
                    for (NSNumber *tickLocation in customTickLocations) {
                        
                        CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText: [xAxisLabels objectAtIndex:labelLocation++] textStyle:axisSet_volume.xAxis.labelTextStyle];
                        
                        newLabel.tickLocation = [tickLocation decimalValue];
                        newLabel.offset = axisSet_volume.xAxis.labelOffset + axisSet_volume.xAxis.majorTickLength;
                        newLabel.offset =  0.0;
                        
                        [customLabels addObject:newLabel];
                        
                        [newLabel release];
                    }
                    
                    axisSet_volume.xAxis.majorTickLocations =	customTickLocations ;
                    axisSet_volume.xAxis.axisLabels =  [NSSet setWithArray:customLabels];	          
                    
                    [customTickLocations release];
                    [xAxisLabels release];
                    
                    
                    //當使用CPAxisLabelingPolicyNone 可以顯示格線
                    x_volume.labelingPolicy = CPTAxisLabelingPolicyNone;
                    
                    //格線格式
                    majorGridLineStyle = [CPTMutableLineStyle lineStyle];
                    majorGridLineStyle.lineWidth = 1.0;
                    majorGridLineStyle.lineColor = [[CPTColor colorWithGenericGray:0.4] colorWithAlphaComponent:0.75];
                    //虛線格式
                    majorGridLineStyle.dashPattern=[NSArray arrayWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:3.0],nil];
                    
                    
                    x_volume.majorGridLineStyle = majorGridLineStyle;                  
            
            
            
            
            [graph_volume reloadData];
            
        }
    }
            //將左右游動位置記錄
            select_left=[ NSString stringWithFormat: @"%i",left_selected]; 
            select_right=[ NSString  stringWithFormat: @"%i",right_selected];  
            
            [cell_intraday_graph_selected_right replaceObjectAtIndex:index_intraday withObject:select_right];
            [cell_intraday_graph_selected_left replaceObjectAtIndex:index_intraday withObject:select_left];            
            
            NSLog(@"select_right=%@",  select_right   );
            NSLog(@"select_left=%@",  select_left   );    
            
            
            
    return YES;  


}
        
               
        
    }
    return YES;
}
#pragma mark -
#pragma mark  走勢圖-限制水平移動 與ＸＹ軸原點的調整
 
//限制手勢僅可以左右滑動 上下移動沒有效果
-(CGPoint)plotSpace:(CPTPlotSpace *)space willDisplaceBy:(CGPoint)displacement {
     return CGPointMake(displacement.x, 0);
}
 

- (CPTPlotRange *)plotSpace:(CPTPlotSpace *)space
     willChangePlotRangeTo:(CPTPlotRange *)newRange
             forCoordinate:(CPTCoordinate)coordinate {
    
    NSLog(@"限制水平移動 與ＸＹ軸原點的調整");
  
    // 只有允許可以右邊移動
    // remove this to have scrolling in both directions
    
    
    if (newRange.locationDouble < 0.0F) {
      // newRange.location = CPTDecimalFromFloat(0.0);
     
    }
    
    // 調整ＸＹ軸永遠都在最左邊與底部;
    // 調整scale-labels能跟軸配合.
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
    if (coordinate == CPTCoordinateX) {
        //如果滑動水平方向 y軸的原點就在新的原點 位置
        axisSet.yAxis.orthogonalCoordinateDecimal = newRange.location;
        axisSet.xAxis.titleLocation = CPTDecimalFromFloat(newRange.locationDouble +
                                                         (newRange.lengthDouble / 2.0F));
    } else {
        axisSet.xAxis.orthogonalCoordinateDecimal = newRange.location;
        axisSet.yAxis.titleLocation = CPTDecimalFromFloat(newRange.locationDouble +
                                                         (newRange.lengthDouble / 2.0F));
    }
    //移動時 y軸移到哪個位置上
   // NSLog(@"x=%i",[[NSDecimalNumber decimalNumberWithDecimal:axisSet.yAxis.orthogonalCoordinateDecimal] intValue] );
    
    //計算新移動走勢圖之後的最高點與最低點,並將此數據傳送到下一個移動完成的事件  didChangePlotRangeForCoordinateㄝ,由此事件來重新定義最高點與最低點,主要是因為回傳的newRange 會蓋掉
    
    for (int x=[[NSDecimalNumber decimalNumberWithDecimal:axisSet.yAxis.orthogonalCoordinateDecimal] intValue]  ; x<[graph_data_aray_real count] ; x++ ) {
        
        NSDictionary *tData = (NSDictionary *)[graph_data_aray_real objectAtIndex:x];
                
        
        if (x==[[NSDecimalNumber decimalNumberWithDecimal:axisSet.yAxis.orthogonalCoordinateDecimal] intValue]   ) {
            high_graph_selected=  [[tData objectForKey:@"close"] floatValue]  ;
            low_graph_selected= [[tData objectForKey:@"close"] floatValue];
        }
        else{
            if ([[tData objectForKey:@"close"] floatValue] >high_graph_selected) {
                high_graph_selected=[[tData objectForKey:@"close"] floatValue];
            }
            if ([[tData objectForKey:@"close"] floatValue] <low_graph_selected) {
                low_graph_selected=[[tData objectForKey:@"close"] floatValue];
            }
            
            
        }
        
        
        
    }
   
     //  NSLog(@"high=%f low=%f",new_high,new_low);
   
      
    
    return newRange;
}

-(void)plotSpace:(CPTPlotSpace *)space didChangePlotRangeForCoordinate:(CPTCoordinate)coordinate{
    //承接由- (CPPlotRange *)plotSpace:(CPPlotSpace *)space willChangePlotRangeTo:(CPPlotRange *)newRangeforCoordinate:(CPCoordinate)coordinate 所計算出來的最高點與最低點,重新設定yRange 這樣的走勢圖在移動時 才能完全與畫面高低相同
    
    plotSpace1.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(low_graph_selected)  length:CPTDecimalFromFloat(high_graph_selected-low_graph_selected)];    
}

#pragma mark -
#pragma mark  走勢圖-在特定位置上加入標籤
//此段程式會影響table cell滑動的速度 主要是因為他將呼叫所有datalable 會駛速度將慢 
 /*
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index{
    // 定义一个白色的 TextStyle
  // NSLog(@"plot=%@ index=%i",plot.identifier,index);
        
    
    
    
    if ([(NSString *)plot.identifier isEqualToString:@"Plot1"]) {
        if (index==100) {
            //特定位置上顯示 標籤
             
            static CPTMutableTextStyle *whiteText = nil;
            
            if (!whiteText) {
                whiteText = [[CPTMutableTextStyle alloc] init];
                whiteText.color = [CPTColor whiteColor ];
            }
            
            CPTTextLayer *newLayer = [[[CPTTextLayer alloc] initWithText:@"FFF" style:whiteText] autorelease];            
            
                         
                      
            return newLayer;               
            
            
        }
        else{
            //非特定位置 不顯示任何東西
                        
            return  (id)[NSNull null];
        }
    
    }    
    else{
        return  (id)[NSNull null];
    }
    
      
    
} 
*/

#pragma mark -
#pragma mark  時區轉換

//標記:時區轉換 從國家碼轉為地區碼
-(NSString *)Symbol_converTo_timeZoneWithName:(NSString*) symbol{
    
    symbol=[symbol uppercaseString];
    
    NSArray *code_array;
    code_array=[symbol componentsSeparatedByString:@"."];
    
    //標記:Add Target need Program 時區轉換
    //可以透過  -(void)timezone_list_knownTimeZoneNames  取出所有時區名稱
    
    if ([code_array count]==2) {
        //非美國國家交易所
        if ([[code_array objectAtIndex:1] isEqualToString:@"HK"]) {
            //香港
            return @"Asia/Hong_Kong";
        }
        else if ([[code_array objectAtIndex:1] isEqualToString:@"TW"] || [[code_array objectAtIndex:1] isEqualToString:@"TWO"]){
            //台灣
            return @"Asia/Taipei";
        }   
        else if ([[code_array objectAtIndex:1] isEqualToString:@"AX"]  ){
            //澳洲
            return @"Australia/Sydney";
        } 
        else if ([[code_array objectAtIndex:1] isEqualToString:@"SS"] || [[code_array objectAtIndex:1] isEqualToString:@"SZ"]){
            //中國
            return @"Asia/Shanghai";
        }  
        else if ([[code_array objectAtIndex:1] isEqualToString:@"TO"] || [[code_array objectAtIndex:1] isEqualToString:@"V"]){
            //加拿大
            return @"America/Toronto";
        } 
        else if ([[code_array objectAtIndex:1] isEqualToString:@"BE"] || [[code_array objectAtIndex:1] isEqualToString:@"BM"]  || [[code_array objectAtIndex:1] isEqualToString:@"DU"] || [[code_array objectAtIndex:1] isEqualToString:@"F"]  || [[code_array objectAtIndex:1] isEqualToString:@"HM"] || [[code_array objectAtIndex:1] isEqualToString:@"HA"] || [[code_array objectAtIndex:1] isEqualToString:@"MU"] || [[code_array objectAtIndex:1] isEqualToString:@"SG"] || [[code_array objectAtIndex:1] isEqualToString:@"DE"]  ){
            //德國
            return @"Europe/Berlin";
        }          
        else if ([[code_array objectAtIndex:1] isEqualToString:@"BO"] || [[code_array objectAtIndex:1] isEqualToString:@"NS"]){
            //印度
            return @"Asia/Kolkata";
        }  
        else if ([[code_array objectAtIndex:1] isEqualToString:@"KS"] || [[code_array objectAtIndex:1] isEqualToString:@"KQ"]){
            //韓國
            return @"Asia/Seoul";
        }
        else if ([[code_array objectAtIndex:1] isEqualToString:@"MI"]  ){
            //義大利
            return @"Europe/Rome";
        } 
        else if ([[code_array objectAtIndex:1] isEqualToString:@"NZ"]  ){
            //紐西蘭
            return @"Pacific/Auckland";
        } 
        else if ([[code_array objectAtIndex:1] isEqualToString:@"PA"] || [[code_array objectAtIndex:1] isEqualToString:@"NX"] ){
            //法國
            return @"Europe/Paris";
        }           
        else if ([[code_array objectAtIndex:1] isEqualToString:@"SA"]  ){
            //巴西
            return @"America/Sao_Paulo";
        }         
        else if ([[code_array objectAtIndex:1] isEqualToString:@"MX"]  ){
            //墨西哥
            return @"America/Mexico_City";
        }           
        else if ([[code_array objectAtIndex:1] isEqualToString:@"SI"]  ){
            //新加坡
            return @"Asia/Singapore";
        }          
        else if ([[code_array objectAtIndex:1] isEqualToString:@"L"]  ){
            //英國
            return @"Europe/London";
        }          
        else{
            //如果 都沒有找到設定 就設定為 美國國家交易所
            return @"America/New_York";            
            
        }
    }
    else{
        //美國國家交易所
        return @"America/New_York";
    }
    
}

#pragma mark -
#pragma mark  記憶體清除



- (void)dealloc {
     
     //[downloadobject release];
    
 
   
  
    [super dealloc];
}

 


@end



